path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
node_modules/react-icons/ti/thumbs-down.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const TiThumbsDown = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m28.3 8.3c-1.2 0-2.4 0.5-3.2 1.3-0.1-0.1-0.2-0.2-0.4-0.3-1.6-1.3-6.1-2.6-9.7-2.6-3.1 0-4.3 0.5-5.4 0.9-0.2 0.1-0.4 0.1-0.5 0.2-1.4 0.5-2.7 2-2.9 3.7l-1.2 9.9c-0.2 1.7 0.8 3.6 2.4 4.1 0.6 0.3 4.2 0.7 6.5 1-0.4 2.1-0.6 4-0.6 6 0 2.3 1.9 4.2 4.2 4.2s4.2-1.9 4.2-4.2c0-3.1 1.1-4.6 2.7-6.2 0.9 1.2 2.3 2 3.9 2 2.8 0 5-2.2 5-5v-10c0-2.7-2.2-5-5-5z m-10 24.2c0 0.5-0.3 0.8-0.8 0.8s-0.8-0.3-0.8-0.8c0-3 0.4-5.4 0.8-7.2l0.5-2.3-2.2 0.3c-1-0.1-6.6-0.7-7.3-0.9-0.1 0-0.2-0.3-0.1-0.5l1.1-10c0-0.4 0.4-0.9 0.7-1 0.2-0.1 0.4-0.1 0.6-0.2 0.9-0.4 1.7-0.7 4.2-0.7 3.2 0 6.9 1.3 7.7 1.9 0.3 0.2 0.6 0.9 0.6 1.4v8.3c0 0.1 0 1.1-1.1 2.2-1.6 1.5-3.9 3.8-3.9 8.7z m11.7-9.2c0 1-0.7 1.7-1.7 1.7s-1.6-0.7-1.6-1.7v-10c0-0.9 0.7-1.6 1.6-1.6s1.7 0.7 1.7 1.6v10z"/></g> </Icon> ) export default TiThumbsDown
app/javascript/mastodon/features/following/index.js
masto-donte-com-br/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import LoadingIndicator from '../../components/loading_indicator'; import { lookupAccount, fetchAccount, fetchFollowing, expandFollowing, } from '../../actions/accounts'; import { FormattedMessage } from 'react-intl'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import HeaderContainer from '../account_timeline/containers/header_container'; import ColumnBackButton from '../../components/column_back_button'; import ScrollableList from '../../components/scrollable_list'; import MissingIndicator from 'mastodon/components/missing_indicator'; import TimelineHint from 'mastodon/components/timeline_hint'; const mapStateToProps = (state, { params: { acct, id } }) => { const accountId = id || state.getIn(['accounts_map', acct]); if (!accountId) { return { isLoading: true, }; } return { accountId, remote: !!(state.getIn(['accounts', accountId, 'acct']) !== state.getIn(['accounts', accountId, 'username'])), remoteUrl: state.getIn(['accounts', accountId, 'url']), isAccount: !!state.getIn(['accounts', accountId]), accountIds: state.getIn(['user_lists', 'following', accountId, 'items']), hasMore: !!state.getIn(['user_lists', 'following', accountId, 'next']), isLoading: state.getIn(['user_lists', 'following', accountId, 'isLoading'], true), blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false), }; }; const RemoteHint = ({ url }) => ( <TimelineHint url={url} resource={<FormattedMessage id='timeline_hint.resources.follows' defaultMessage='Follows' />} /> ); RemoteHint.propTypes = { url: PropTypes.string.isRequired, }; export default @connect(mapStateToProps) class Following extends ImmutablePureComponent { static propTypes = { params: PropTypes.shape({ acct: PropTypes.string, id: PropTypes.string, }).isRequired, accountId: PropTypes.string, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, hasMore: PropTypes.bool, isLoading: PropTypes.bool, blockedBy: PropTypes.bool, isAccount: PropTypes.bool, remote: PropTypes.bool, remoteUrl: PropTypes.string, multiColumn: PropTypes.bool, }; _load () { const { accountId, isAccount, dispatch } = this.props; if (!isAccount) dispatch(fetchAccount(accountId)); dispatch(fetchFollowing(accountId)); } componentDidMount () { const { params: { acct }, accountId, dispatch } = this.props; if (accountId) { this._load(); } else { dispatch(lookupAccount(acct)); } } componentDidUpdate (prevProps) { const { params: { acct }, accountId, dispatch } = this.props; if (prevProps.accountId !== accountId && accountId) { this._load(); } else if (prevProps.params.acct !== acct) { dispatch(lookupAccount(acct)); } } handleLoadMore = debounce(() => { this.props.dispatch(expandFollowing(this.props.accountId)); }, 300, { leading: true }); render () { const { accountIds, hasMore, blockedBy, isAccount, multiColumn, isLoading, remote, remoteUrl } = this.props; if (!isAccount) { return ( <Column> <MissingIndicator /> </Column> ); } if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } let emptyMessage; if (blockedBy) { emptyMessage = <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' />; } else if (remote && accountIds.isEmpty()) { emptyMessage = <RemoteHint url={remoteUrl} />; } else { emptyMessage = <FormattedMessage id='account.follows.empty' defaultMessage="This user doesn't follow anyone yet." />; } const remoteMessage = remote ? <RemoteHint url={remoteUrl} /> : null; return ( <Column> <ColumnBackButton multiColumn={multiColumn} /> <ScrollableList scrollKey='following' hasMore={hasMore} isLoading={isLoading} onLoadMore={this.handleLoadMore} prepend={<HeaderContainer accountId={this.props.accountId} hideTabs />} alwaysPrepend append={remoteMessage} emptyMessage={emptyMessage} bindToDocument={!multiColumn} > {blockedBy ? [] : accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />, )} </ScrollableList> </Column> ); } }
modules/icons/droplets.js
hakonhk/vaerhona
import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class Icon extends Component { static defaultProps = { width: '20px', height: '20px', fill: '#000000', }; static propTypes = { width: PropTypes.string, height: PropTypes.string, fill: PropTypes.string, }; render() { const { width, height, fill } = this.props; const style = { width, height, }; return ( <svg version="1.1" style={style} viewBox="0 0 20 20"> <path d="M3.955 0.093c-0.015-0.124-0.22-0.124-0.234 0-0.511 4.115-3.121 4.963-3.121 7.823 0 1.767 1.482 3.199 3.238 3.199s3.238-1.432 3.238-3.199c0-2.86-2.61-3.708-3.121-7.823zM16.279 0.093c-0.016-0.124-0.219-0.124-0.234 0-0.511 4.115-3.121 4.963-3.121 7.823 0 1.767 1.482 3.199 3.238 3.199s3.238-1.432 3.238-3.199c0-2.86-2.61-3.708-3.121-7.823zM9.883 8.978c-0.511 4.115-3.121 4.962-3.121 7.822 0 1.768 1.482 3.2 3.238 3.2s3.238-1.433 3.238-3.2c0-2.859-2.61-3.707-3.121-7.822-0.015-0.125-0.219-0.125-0.234 0z" fill={fill} ></path> </svg> ); } }
src/TrailsPost.js
melaniebmn/peaktrails
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import SectionHeading from './SectionHeading'; import imgIcons from './assets/img/icons--trail.png'; import trails from './trails.json'; const ImgContainer = styled.figure` overflow: hidden; display: flex; align-items: center; margin: 0 auto 45px; img { width: 100%; } @media only screen and (min-width: 625px) { height: 450px; } `; const ContentContainer = styled.div` width: 85%; max-width: 855px; margin: 0 auto; `; const TrailInfo = styled.ul` margin: 0 auto 35px; li { position: relative; min-height: 60px; justify-content: center; margin: 0 0 30px; padding: 0 10px 0 75px; &:before { position: absolute; top: 0; left: 0; width: 60px; height: 60px; content: ''; background: var(--accent-color); border-radius: 100%; } &:after { position: absolute; top: 7.5px; left: 7.5px; width: 45px; height: 40px; content: ''; background: url(${imgIcons}); } h4, p { font-size: 20px; } &:nth-child(1):after { background-position: -3px 82px; } &:nth-child(2):after { background-position: -104px 42px; } &:nth-child(3):after { background-position: -107px -1px; } &:nth-child(4):after { background-position: -3px 0; } &:nth-child(5):after { background-position: -51px -8px; } &:nth-child(6):after { background-position: -56px 42px; } &:nth-child(7):after { background-position: -55px 80px; } &:nth-child(8):after { background-position: -6px 42px; } &:nth-child(9):after { background-position: -108px 82px; } } `; const Subheading = styled.h3` font-size: 22px; text-align: center; margin: 75px auto 35px; padding: 20px 0; border-top: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color); `; const TrailText = styled.p` font-family: 'Cantarell', sans-serif; margin: 0 auto 35px; `; const TrailsPost = ({ match: { params: { trailId } } }) => { const trail = trails.find( _trail => _trail.id === trailId, ); return ( <section> <SectionHeading text={trail.name} /> <ImgContainer> <img src={require(`assets/img/${trail.img}`)} alt="Featured Trail" /> </ImgContainer> <ContentContainer> <TrailInfo className="grid"> <li className="grid__col-md-4 grid__col-sm-6 grid__col-12"> <h4>Region:</h4> <p>{trail.region}</p> </li> <li className="grid__col-md-4 grid__col-sm-6 grid__col-12"> <h4>Difficulty:</h4> <p>{trail.difficulty}</p> </li> <li className="grid__col-md-4 grid__col-sm-6 grid__col-12"> <h4>Time:</h4> <p>{trail.time} hrs</p> </li> <li className="grid__col-md-4 grid__col-sm-6 grid__col-12"> <h4>Distance:</h4> <p>{trail.distance} km</p> </li> <li className="grid__col-md-4 grid__col-sm-6 grid__col-12"> <h4>Elevation Gain:</h4> <p>{trail.gain}</p> </li> <li className="grid__col-md-4 grid__col-sm-6 grid__col-12"> <h4>Season:</h4> <p>{trail.season}</p> </li> <li className="grid__col-md-4 grid__col-sm-6 grid__col-12"> <h4>Camping:</h4> <p>{trail.camping}</p> </li> <li className="grid__col-md-4 grid__col-sm-6 grid__col-12"> <h4>Dog Friendly:</h4> <p>{trail.dogFriendly}</p> </li> <li className="grid__col-md-4 grid__col-sm-6 grid__col-12"> <h4>Public Transit:</h4> <p>{trail.transit}</p> </li> </TrailInfo> {trail.description.map((p, i) => <TrailText key={i}>{p}</TrailText> )} <Subheading>How to get there</Subheading> <TrailText>Estimated Driving Time from Vancouver: {trail.drivingTime}</TrailText> {trail.drivingInstructions.map((p, i) => <TrailText key={i}>{p}</TrailText> )} <Subheading>Dogs</Subheading> <TrailText>{trail.dogs}</TrailText> <Subheading>Toilets</Subheading> <TrailText>{trail.toilets}</TrailText> </ContentContainer> </section> ); }; TrailsPost.propTypes = { match: PropTypes.shape({ params: PropTypes.shape({ trailId: PropTypes.string.isRequired }).isRequired }).isRequired }; export default styled(TrailsPost)` ul, h3, p { max-width: 855px; width: 85%; } a { color: var(--accent-color); } `;
src/index.js
s89206x/WebpackSemple_map
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
ajax/libs/yui/3.7.3/datatable-body/datatable-body-coverage.js
zhengyongbo/cdnjs
if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if (!coverage.lines[line]){ coverage.calledLines++; } coverage.lines[line]++; }; _yuitest_coverfunc = function(src, name, line){ var coverage = _yuitest_coverage[src], funcId = name + ":" + line; if (!coverage.functions[funcId]){ coverage.calledFunctions++; } coverage.functions[funcId]++; }; } _yuitest_coverage["build/datatable-body/datatable-body.js"] = { lines: {}, functions: {}, coveredLines: 0, calledLines: 0, coveredFunctions: 0, calledFunctions: 0, path: "build/datatable-body/datatable-body.js", code: [] }; _yuitest_coverage["build/datatable-body/datatable-body.js"].code=["YUI.add('datatable-body', function (Y, NAME) {","","/**","View class responsible for rendering the `<tbody>` section of a table. Used as","the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.","","@module datatable","@submodule datatable-body","@since 3.5.0","**/","var Lang = Y.Lang,"," isArray = Lang.isArray,"," isNumber = Lang.isNumber,"," isString = Lang.isString,"," fromTemplate = Lang.sub,"," htmlEscape = Y.Escape.html,"," toArray = Y.Array,"," bind = Y.bind,"," YObject = Y.Object;","","/**","View class responsible for rendering the `<tbody>` section of a table. Used as","the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.","","Translates the provided `modelList` into a rendered `<tbody>` based on the data","in the constituent Models, altered or ammended by any special column","configurations.","","The `columns` configuration, passed to the constructor, determines which","columns will be rendered.","","The rendering process involves constructing an HTML template for a complete row","of data, built by concatenating a customized copy of the instance's","`CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is","then populated with values from each Model in the `modelList`, aggregating a","complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied.","","Supported properties of the column objects include:",""," * `key` - Used to link a column to an attribute in a Model."," * `name` - Used for columns that don't relate to an attribute in the Model"," (`formatter` or `nodeFormatter` only) if the implementer wants a"," predictable name to refer to in their CSS."," * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this"," column only."," * `formatter` - Used to customize or override the content value from the"," Model. These do not have access to the cell or row Nodes and should"," return string (HTML) content."," * `nodeFormatter` - Used to provide content for a cell as well as perform any"," custom modifications on the cell or row Node that could not be performed by"," `formatter`s. Should be used sparingly for better performance."," * `emptyCellValue` - String (HTML) value to use if the Model data for a"," column, or the content generated by a `formatter`, is the empty string,"," `null`, or `undefined`."," * `allowHTML` - Set to `true` if a column value, `formatter`, or"," `emptyCellValue` can contain HTML. This defaults to `false` to protect"," against XSS."," * `className` - Space delimited CSS classes to add to all `<td>`s in a column.","","Column `formatter`s are passed an object (`o`) with the following properties:",""," * `value` - The current value of the column's associated attribute, if any."," * `data` - An object map of Model keys to their current values."," * `record` - The Model instance."," * `column` - The column configuration object for the current column."," * `className` - Initially empty string to allow `formatter`s to add CSS "," classes to the cell's `<td>`."," * `rowIndex` - The zero-based row number."," * `rowClass` - Initially empty string to allow `formatter`s to add CSS"," classes to the cell's containing row `<tr>`.","","They may return a value or update `o.value` to assign specific HTML content. A","returned value has higher precedence.","","Column `nodeFormatter`s are passed an object (`o`) with the following","properties:",""," * `value` - The current value of the column's associated attribute, if any."," * `td` - The `<td>` Node instance."," * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`."," When adding content to the cell, prefer appending into this property."," * `data` - An object map of Model keys to their current values."," * `record` - The Model instance."," * `column` - The column configuration object for the current column."," * `rowIndex` - The zero-based row number.","","They are expected to inject content into the cell's Node directly, including","any \"empty\" cell content. Each `nodeFormatter` will have access through the","Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as","it will not be attached yet.","","If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be","`destroy()`ed to remove them from the Node cache and free up memory. The DOM","elements will remain as will any content added to them. _It is highly","advisable to always return `false` from your `nodeFormatter`s_.","","@class BodyView","@namespace DataTable","@extends View","@since 3.5.0","**/","Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], {"," // -- Instance properties -------------------------------------------------",""," /**"," HTML template used to create table cells.",""," @property CELL_TEMPLATE"," @type {HTML}"," @default '<td {headers} class=\"{className}\">{content}</td>'"," @since 3.5.0"," **/"," CELL_TEMPLATE: '<td {headers} class=\"{className}\">{content}</td>',",""," /**"," CSS class applied to even rows. This is assigned at instantiation."," "," For DataTable, this will be `yui3-datatable-even`.",""," @property CLASS_EVEN"," @type {String}"," @default 'yui3-table-even'"," @since 3.5.0"," **/"," //CLASS_EVEN: null",""," /**"," CSS class applied to odd rows. This is assigned at instantiation."," "," When used by DataTable instances, this will be `yui3-datatable-odd`.",""," @property CLASS_ODD"," @type {String}"," @default 'yui3-table-odd'"," @since 3.5.0"," **/"," //CLASS_ODD: null",""," /**"," HTML template used to create table rows.",""," @property ROW_TEMPLATE"," @type {HTML}"," @default '<tr id=\"{rowId}\" data-yui3-record=\"{clientId}\" class=\"{rowClass}\">{content}</tr>'"," @since 3.5.0"," **/"," ROW_TEMPLATE : '<tr id=\"{rowId}\" data-yui3-record=\"{clientId}\" class=\"{rowClass}\">{content}</tr>',",""," /**"," The object that serves as the source of truth for column and row data."," This property is assigned at instantiation from the `host` property of"," the configuration object passed to the constructor.",""," @property host"," @type {Object}"," @default (initially unset)"," @since 3.5.0"," **/"," //TODO: should this be protected?"," //host: null,",""," /**"," HTML templates used to create the `<tbody>` containing the table rows.",""," @property TBODY_TEMPLATE"," @type {HTML}"," @default '<tbody class=\"{className}\">{content}</tbody>'"," @since 3.6.0"," **/"," TBODY_TEMPLATE: '<tbody class=\"{className}\"></tbody>',",""," // -- Public methods ------------------------------------------------------",""," /**"," Returns the `<td>` Node from the given row and column index. Alternately,"," the `seed` can be a Node. If so, the nearest ancestor cell is returned."," If the `seed` is a cell, it is returned. If there is no cell at the given"," coordinates, `null` is returned.",""," Optionally, include an offset array or string to return a cell near the"," cell identified by the `seed`. The offset can be an array containing the"," number of rows to shift followed by the number of columns to shift, or one"," of \"above\", \"below\", \"next\", or \"previous\".",""," <pre><code>// Previous cell in the previous row"," var cell = table.getCell(e.target, [-1, -1]);",""," // Next cell"," var cell = table.getCell(e.target, 'next');"," var cell = table.getCell(e.taregt, [0, 1];</pre></code>",""," @method getCell"," @param {Number[]|Node} seed Array of row and column indexes, or a Node that"," is either the cell itself or a descendant of one."," @param {Number[]|String} [shift] Offset by which to identify the returned"," cell Node"," @return {Node}"," @since 3.5.0"," **/"," getCell: function (seed, shift) {"," var tbody = this.tbodyNode,"," row, cell, index, rowIndexOffset;",""," if (seed && tbody) {"," if (isArray(seed)) {"," row = tbody.get('children').item(seed[0]);"," cell = row && row.get('children').item(seed[1]);"," } else if (Y.instanceOf(seed, Y.Node)) {"," cell = seed.ancestor('.' + this.getClassName('cell'), true);"," }",""," if (cell && shift) {"," rowIndexOffset = tbody.get('firstChild.rowIndex');"," if (isString(shift)) {"," // TODO this should be a static object map"," switch (shift) {"," case 'above' : shift = [-1, 0]; break;"," case 'below' : shift = [1, 0]; break;"," case 'next' : shift = [0, 1]; break;"," case 'previous': shift = [0, -1]; break;"," }"," }",""," if (isArray(shift)) {"," index = cell.get('parentNode.rowIndex') +"," shift[0] - rowIndexOffset;"," row = tbody.get('children').item(index);",""," index = cell.get('cellIndex') + shift[1];"," cell = row && row.get('children').item(index);"," }"," }"," }"," "," return cell || null;"," },",""," /**"," Returns the generated CSS classname based on the input. If the `host`"," attribute is configured, it will attempt to relay to its `getClassName`"," or use its static `NAME` property as a string base."," "," If `host` is absent or has neither method nor `NAME`, a CSS classname"," will be generated using this class's `NAME`.",""," @method getClassName"," @param {String} token* Any number of token strings to assemble the"," classname from."," @return {String}"," @protected"," @since 3.5.0"," **/"," getClassName: function () {"," var host = this.host,"," args;",""," if (host && host.getClassName) {"," return host.getClassName.apply(host, arguments);"," } else {"," args = toArray(arguments);"," args.unshift(this.constructor.NAME);"," return Y.ClassNameManager.getClassName"," .apply(Y.ClassNameManager, args);"," }"," },",""," /**"," Returns the Model associated to the row Node or id provided. Passing the"," Node or id for a descendant of the row also works.",""," If no Model can be found, `null` is returned.",""," @method getRecord"," @param {String|Node} seed Row Node or `id`, or one for a descendant of a row"," @return {Model}"," @since 3.5.0"," **/"," getRecord: function (seed) {"," var modelList = this.get('modelList'),"," tbody = this.tbodyNode,"," row = null,"," record;",""," if (tbody) {"," if (isString(seed)) {"," seed = tbody.one('#' + seed);"," }",""," if (Y.instanceOf(seed, Y.Node)) {"," row = seed.ancestor(function (node) {"," return node.get('parentNode').compareTo(tbody);"," }, true);",""," record = row &&"," modelList.getByClientId(row.getData('yui3-record'));"," }"," }",""," return record || null;"," },",""," /**"," Returns the `<tr>` Node from the given row index, Model, or Model's"," `clientId`. If the rows haven't been rendered yet, or if the row can't be"," found by the input, `null` is returned.",""," @method getRow"," @param {Number|String|Model} id Row index, Model instance, or clientId"," @return {Node}"," @since 3.5.0"," **/"," getRow: function (id) {"," var tbody = this.tbodyNode,"," row = null;",""," if (tbody) {"," if (id) {"," id = this._idMap[id.get ? id.get('clientId') : id] || id;"," }",""," row = isNumber(id) ?"," tbody.get('children').item(id) :"," tbody.one('#' + id);"," }",""," return row;"," },",""," /**"," Creates the table's `<tbody>` content by assembling markup generated by"," populating the `ROW\\_TEMPLATE`, and `CELL\\_TEMPLATE` templates with content"," from the `columns` and `modelList` attributes.",""," The rendering process happens in three stages:",""," 1. A row template is assembled from the `columns` attribute (see"," `_createRowTemplate`)",""," 2. An HTML string is built up by concatening the application of the data in"," each Model in the `modelList` to the row template. For cells with"," `formatter`s, the function is called to generate cell content. Cells"," with `nodeFormatter`s are ignored. For all other cells, the data value"," from the Model attribute for the given column key is used. The"," accumulated row markup is then inserted into the container.",""," 3. If any column is configured with a `nodeFormatter`, the `modelList` is"," iterated again to apply the `nodeFormatter`s.",""," Supported properties of the column objects include:",""," * `key` - Used to link a column to an attribute in a Model."," * `name` - Used for columns that don't relate to an attribute in the Model"," (`formatter` or `nodeFormatter` only) if the implementer wants a"," predictable name to refer to in their CSS."," * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in"," this column only."," * `formatter` - Used to customize or override the content value from the"," Model. These do not have access to the cell or row Nodes and should"," return string (HTML) content."," * `nodeFormatter` - Used to provide content for a cell as well as perform"," any custom modifications on the cell or row Node that could not be"," performed by `formatter`s. Should be used sparingly for better"," performance."," * `emptyCellValue` - String (HTML) value to use if the Model data for a"," column, or the content generated by a `formatter`, is the empty string,"," `null`, or `undefined`."," * `allowHTML` - Set to `true` if a column value, `formatter`, or"," `emptyCellValue` can contain HTML. This defaults to `false` to protect"," against XSS."," * `className` - Space delimited CSS classes to add to all `<td>`s in a"," column.",""," Column `formatter`s are passed an object (`o`) with the following"," properties:",""," * `value` - The current value of the column's associated attribute, if"," any."," * `data` - An object map of Model keys to their current values."," * `record` - The Model instance."," * `column` - The column configuration object for the current column."," * `className` - Initially empty string to allow `formatter`s to add CSS "," classes to the cell's `<td>`."," * `rowIndex` - The zero-based row number."," * `rowClass` - Initially empty string to allow `formatter`s to add CSS"," classes to the cell's containing row `<tr>`.",""," They may return a value or update `o.value` to assign specific HTML"," content. A returned value has higher precedence.",""," Column `nodeFormatter`s are passed an object (`o`) with the following"," properties:",""," * `value` - The current value of the column's associated attribute, if"," any."," * `td` - The `<td>` Node instance."," * `cell` - The `<div>` liner Node instance if present, otherwise, the"," `<td>`. When adding content to the cell, prefer appending into this"," property."," * `data` - An object map of Model keys to their current values."," * `record` - The Model instance."," * `column` - The column configuration object for the current column."," * `rowIndex` - The zero-based row number.",""," They are expected to inject content into the cell's Node directly, including"," any \"empty\" cell content. Each `nodeFormatter` will have access through the"," Node API to all cells and rows in the `<tbody>`, but not to the `<table>`,"," as it will not be attached yet.",""," If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be"," `destroy()`ed to remove them from the Node cache and free up memory. The"," DOM elements will remain as will any content added to them. _It is highly"," advisable to always return `false` from your `nodeFormatter`s_.",""," @method render"," @return {BodyView} The instance"," @chainable"," @since 3.5.0"," **/"," render: function () {"," var table = this.get('container'),"," data = this.get('modelList'),"," columns = this.get('columns'),"," tbody = this.tbodyNode ||"," (this.tbodyNode = this._createTBodyNode());"," "," // Needed for mutation"," this._createRowTemplate(columns);",""," if (data) {"," tbody.setHTML(this._createDataHTML(columns));",""," this._applyNodeFormatters(tbody, columns);"," }",""," if (tbody.get('parentNode') !== table) {"," table.appendChild(tbody);"," }",""," this.bindUI();",""," return this;"," },",""," // -- Protected and private methods ---------------------------------------"," /**"," Handles changes in the source's columns attribute. Redraws the table data.",""," @method _afterColumnsChange"," @param {EventFacade} e The `columnsChange` event object"," @protected"," @since 3.5.0"," **/"," // TODO: Preserve existing DOM"," // This will involve parsing and comparing the old and new column configs"," // and reacting to four types of changes:"," // 1. formatter, nodeFormatter, emptyCellValue changes"," // 2. column deletions"," // 3. column additions"," // 4. column moves (preserve cells)"," _afterColumnsChange: function (e) {"," this.render();"," },",""," /**"," Handles modelList changes, including additions, deletions, and updates.",""," Modifies the existing table DOM accordingly.",""," @method _afterDataChange"," @param {EventFacade} e The `change` event from the ModelList"," @protected"," @since 3.5.0"," **/"," _afterDataChange: function (e) {"," //var type = e.type.slice(e.type.lastIndexOf(':') + 1);",""," // TODO: Isolate changes"," this.render();"," },",""," /**"," Handles replacement of the modelList.",""," Rerenders the `<tbody>` contents.",""," @method _afterModelListChange"," @param {EventFacade} e The `modelListChange` event"," @protected"," @since 3.6.0"," **/"," _afterModelListChange: function (e) {"," var handles = this._eventHandles;",""," if (handles.dataChange) {"," handles.dataChange.detach();"," delete handles.dataChange;"," this.bindUI();"," }",""," if (this.tbodyNode) {"," this.render();"," }"," },",""," /**"," Iterates the `modelList`, and calls any `nodeFormatter`s found in the"," `columns` param on the appropriate cell Nodes in the `tbody`.",""," @method _applyNodeFormatters"," @param {Node} tbody The `<tbody>` Node whose columns to update"," @param {Object[]} columns The column configurations"," @protected"," @since 3.5.0"," **/"," _applyNodeFormatters: function (tbody, columns) {"," var host = this.host,"," data = this.get('modelList'),"," formatters = [],"," linerQuery = '.' + this.getClassName('liner'),"," rows, i, len;",""," // Only iterate the ModelList again if there are nodeFormatters"," for (i = 0, len = columns.length; i < len; ++i) {"," if (columns[i].nodeFormatter) {"," formatters.push(i);"," }"," }",""," if (data && formatters.length) {"," rows = tbody.get('childNodes');",""," data.each(function (record, index) {"," var formatterData = {"," data : record.toJSON(),"," record : record,"," rowIndex : index"," },"," row = rows.item(index),"," i, len, col, key, cells, cell, keep;","",""," if (row) {"," cells = row.get('childNodes');"," for (i = 0, len = formatters.length; i < len; ++i) {"," cell = cells.item(formatters[i]);",""," if (cell) {"," col = formatterData.column = columns[formatters[i]];"," key = col.key || col.id;",""," formatterData.value = record.get(key);"," formatterData.td = cell;"," formatterData.cell = cell.one(linerQuery) || cell;",""," keep = col.nodeFormatter.call(host,formatterData);",""," if (keep === false) {"," // Remove from the Node cache to reduce"," // memory footprint. This also purges events,"," // which you shouldn't be scoping to a cell"," // anyway. You've been warned. Incidentally,"," // you should always return false. Just sayin."," cell.destroy(true);"," }"," }"," }"," }"," });"," }"," },",""," /**"," Binds event subscriptions from the UI and the host (if assigned).",""," @method bindUI"," @protected"," @since 3.5.0"," **/"," bindUI: function () {"," var handles = this._eventHandles,"," modelList = this.get('modelList'),"," changeEvent = modelList.model.NAME + ':change';",""," if (!handles.columnsChange) {"," handles.columnsChange = this.after('columnsChange',"," bind('_afterColumnsChange', this));"," }",""," if (modelList && !handles.dataChange) {"," handles.dataChange = modelList.after("," ['add', 'remove', 'reset', changeEvent],"," bind('_afterDataChange', this));"," }"," },",""," /**"," Iterates the `modelList` and applies each Model to the `_rowTemplate`,"," allowing any column `formatter` or `emptyCellValue` to override cell"," content for the appropriate column. The aggregated HTML string is"," returned.",""," @method _createDataHTML"," @param {Object[]} columns The column configurations to customize the"," generated cell content or class names"," @return {HTML} The markup for all Models in the `modelList`, each applied"," to the `_rowTemplate`"," @protected"," @since 3.5.0"," **/"," _createDataHTML: function (columns) {"," var data = this.get('modelList'),"," html = '';",""," if (data) {"," data.each(function (model, index) {"," html += this._createRowHTML(model, index, columns);"," }, this);"," }",""," return html;"," },",""," /**"," Applies the data of a given Model, modified by any column formatters and"," supplemented by other template values to the instance's `_rowTemplate` (see"," `_createRowTemplate`). The generated string is then returned.",""," The data from Model's attributes is fetched by `toJSON` and this data"," object is appended with other properties to supply values to {placeholders}"," in the template. For a template generated from a Model with 'foo' and 'bar'"," attributes, the data object would end up with the following properties"," before being used to populate the `_rowTemplate`:",""," * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute."," * `foo` - The value to populate the 'foo' column cell content. This"," value will be the value stored in the Model's `foo` attribute, or the"," result of the column's `formatter` if assigned. If the value is '', "," `null`, or `undefined`, and the column's `emptyCellValue` is assigned,"," that value will be used."," * `bar` - Same for the 'bar' column cell content."," * `foo-className` - String of CSS classes to apply to the `<td>`."," * `bar-className` - Same."," * `rowClass` - String of CSS classes to apply to the `<tr>`. This"," will be the odd/even class per the specified index plus any additional"," classes assigned by column formatters (via `o.rowClass`).",""," Because this object is available to formatters, any additional properties"," can be added to fill in custom {placeholders} in the `_rowTemplate`.",""," @method _createRowHTML"," @param {Model} model The Model instance to apply to the row template"," @param {Number} index The index the row will be appearing"," @param {Object[]} columns The column configurations"," @return {HTML} The markup for the provided Model, less any `nodeFormatter`s"," @protected"," @since 3.5.0"," **/"," _createRowHTML: function (model, index, columns) {"," var data = model.toJSON(),"," clientId = model.get('clientId'),"," values = {"," rowId : this._getRowId(clientId),"," clientId: clientId,"," rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN"," },"," host = this.host || this,"," i, len, col, token, value, formatterData;",""," for (i = 0, len = columns.length; i < len; ++i) {"," col = columns[i];"," value = data[col.key];"," token = col._id || col.key;",""," values[token + '-className'] = '';",""," if (col.formatter) {"," formatterData = {"," value : value,"," data : data,"," column : col,"," record : model,"," className: '',"," rowClass : '',"," rowIndex : index"," };",""," if (typeof col.formatter === 'string') {"," if (value !== undefined) {"," // TODO: look for known formatters by string name"," value = fromTemplate(col.formatter, formatterData);"," }"," } else {"," // Formatters can either return a value"," value = col.formatter.call(host, formatterData);",""," // or update the value property of the data obj passed"," if (value === undefined) {"," value = formatterData.value;"," }",""," values[token + '-className'] = formatterData.className;"," values.rowClass += ' ' + formatterData.rowClass;"," }"," }",""," if (value === undefined || value === null || value === '') {"," value = col.emptyCellValue || '';"," }",""," values[token] = col.allowHTML ? value : htmlEscape(value);",""," values.rowClass = values.rowClass.replace(/\\s+/g, ' ');"," }",""," return fromTemplate(this._rowTemplate, values);"," },",""," /**"," Creates a custom HTML template string for use in generating the markup for"," individual table rows with {placeholder}s to capture data from the Models"," in the `modelList` attribute or from column `formatter`s.",""," Assigns the `_rowTemplate` property.",""," @method _createRowTemplate"," @param {Object[]} columns Array of column configuration objects"," @protected"," @since 3.5.0"," **/"," _createRowTemplate: function (columns) {"," var html = '',"," cellTemplate = this.CELL_TEMPLATE,"," i, len, col, key, token, headers, tokenValues;",""," for (i = 0, len = columns.length; i < len; ++i) {"," col = columns[i];"," key = col.key;"," token = col._id || key;"," // Only include headers if there are more than one"," headers = (col._headers || []).length > 1 ?"," 'headers=\"' + col._headers.join(' ') + '\"' : '';",""," tokenValues = {"," content : '{' + token + '}',"," headers : headers,"," className: this.getClassName('col', token) + ' ' +"," (col.className || '') + ' ' +"," this.getClassName('cell') +"," ' {' + token + '-className}'"," };",""," if (col.nodeFormatter) {"," // Defer all node decoration to the formatter"," tokenValues.content = '';"," }",""," html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues);"," }",""," this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, {"," content: html"," });"," },",""," /**"," Creates the `<tbody>` node that will store the data rows.",""," @method _createTBodyNode"," @return {Node}"," @protected"," @since 3.6.0"," **/"," _createTBodyNode: function () {"," return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, {"," className: this.getClassName('data')"," }));"," },",""," /**"," Destroys the instance.",""," @method destructor"," @protected"," @since 3.5.0"," **/"," destructor: function () {"," (new Y.EventHandle(YObject.values(this._eventHandles))).detach();"," },",""," /**"," Holds the event subscriptions needing to be detached when the instance is"," `destroy()`ed.",""," @property _eventHandles"," @type {Object}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_eventHandles: null,",""," /**"," Returns the row ID associated with a Model's clientId.",""," @method _getRowId"," @param {String} clientId The Model clientId"," @return {String}"," @protected"," **/"," _getRowId: function (clientId) {"," return this._idMap[clientId] || (this._idMap[clientId] = Y.guid());"," },",""," /**"," Map of Model clientIds to row ids.",""," @property _idMap"," @type {Object}"," @protected"," **/"," //_idMap,",""," /**"," Initializes the instance. Reads the following configuration properties in"," addition to the instance attributes:",""," * `columns` - (REQUIRED) The initial column information"," * `host` - The object to serve as source of truth for column info and"," for generating class names",""," @method initializer"," @param {Object} config Configuration data"," @protected"," @since 3.5.0"," **/"," initializer: function (config) {"," this.host = config.host;",""," this._eventHandles = {"," modelListChange: this.after('modelListChange',"," bind('_afterModelListChange', this))"," };"," this._idMap = {};",""," this.CLASS_ODD = this.getClassName('odd');"," this.CLASS_EVEN = this.getClassName('even');",""," }",""," /**"," The HTML template used to create a full row of markup for a single Model in"," the `modelList` plus any customizations defined in the column"," configurations.",""," @property _rowTemplate"," @type {HTML}"," @default (initially unset)"," @protected"," @since 3.5.0"," **/"," //_rowTemplate: null","});","","","}, '@VERSION@', {\"requires\": [\"datatable-core\", \"view\", \"classnamemanager\"]});"]; _yuitest_coverage["build/datatable-body/datatable-body.js"].lines = {"1":0,"11":0,"102":0,"201":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"212":0,"213":0,"214":0,"216":0,"217":0,"218":0,"219":0,"220":0,"224":0,"225":0,"227":0,"229":0,"230":0,"235":0,"254":0,"257":0,"258":0,"260":0,"261":0,"262":0,"279":0,"284":0,"285":0,"286":0,"289":0,"290":0,"291":0,"294":0,"299":0,"313":0,"316":0,"317":0,"318":0,"321":0,"326":0,"420":0,"427":0,"429":0,"430":0,"432":0,"435":0,"436":0,"439":0,"441":0,"461":0,"478":0,"492":0,"494":0,"495":0,"496":0,"497":0,"500":0,"501":0,"516":0,"523":0,"524":0,"525":0,"529":0,"530":0,"532":0,"533":0,"542":0,"543":0,"544":0,"545":0,"547":0,"548":0,"549":0,"551":0,"552":0,"553":0,"555":0,"557":0,"563":0,"580":0,"584":0,"585":0,"589":0,"590":0,"611":0,"614":0,"615":0,"616":0,"620":0,"659":0,"669":0,"670":0,"671":0,"672":0,"674":0,"676":0,"677":0,"687":0,"688":0,"690":0,"694":0,"697":0,"698":0,"701":0,"702":0,"706":0,"707":0,"710":0,"712":0,"715":0,"731":0,"735":0,"736":0,"737":0,"738":0,"740":0,"743":0,"752":0,"754":0,"757":0,"760":0,"774":0,"787":0,"811":0,"837":0,"839":0,"843":0,"845":0,"846":0}; _yuitest_coverage["build/datatable-body/datatable-body.js"].functions = {"getCell:200":0,"getClassName:253":0,"(anonymous 2):290":0,"getRecord:278":0,"getRow:312":0,"render:419":0,"_afterColumnsChange:460":0,"_afterDataChange:474":0,"_afterModelListChange:491":0,"(anonymous 3):532":0,"_applyNodeFormatters:515":0,"bindUI:579":0,"(anonymous 4):615":0,"_createDataHTML:610":0,"_createRowHTML:658":0,"_createRowTemplate:730":0,"_createTBodyNode:773":0,"destructor:786":0,"_getRowId:810":0,"initializer:836":0,"(anonymous 1):1":0}; _yuitest_coverage["build/datatable-body/datatable-body.js"].coveredLines = 134; _yuitest_coverage["build/datatable-body/datatable-body.js"].coveredFunctions = 21; _yuitest_coverline("build/datatable-body/datatable-body.js", 1); YUI.add('datatable-body', function (Y, NAME) { /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ _yuitest_coverfunc("build/datatable-body/datatable-body.js", "(anonymous 1)", 1); _yuitest_coverline("build/datatable-body/datatable-body.js", 11); var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object; /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. Translates the provided `modelList` into a rendered `<tbody>` based on the data in the constituent Models, altered or ammended by any special column configurations. The `columns` configuration, passed to the constructor, determines which columns will be rendered. The rendering process involves constructing an HTML template for a complete row of data, built by concatenating a customized copy of the instance's `CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is then populated with values from each Model in the `modelList`, aggregating a complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @class BodyView @namespace DataTable @extends View @since 3.5.0 **/ _yuitest_coverline("build/datatable-body/datatable-body.js", 102); Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], { // -- Instance properties ------------------------------------------------- /** HTML template used to create table cells. @property CELL_TEMPLATE @type {HTML} @default '<td {headers} class="{className}">{content}</td>' @since 3.5.0 **/ CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>', /** CSS class applied to even rows. This is assigned at instantiation. For DataTable, this will be `yui3-datatable-even`. @property CLASS_EVEN @type {String} @default 'yui3-table-even' @since 3.5.0 **/ //CLASS_EVEN: null /** CSS class applied to odd rows. This is assigned at instantiation. When used by DataTable instances, this will be `yui3-datatable-odd`. @property CLASS_ODD @type {String} @default 'yui3-table-odd' @since 3.5.0 **/ //CLASS_ODD: null /** HTML template used to create table rows. @property ROW_TEMPLATE @type {HTML} @default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>' @since 3.5.0 **/ ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>', /** The object that serves as the source of truth for column and row data. This property is assigned at instantiation from the `host` property of the configuration object passed to the constructor. @property host @type {Object} @default (initially unset) @since 3.5.0 **/ //TODO: should this be protected? //host: null, /** HTML templates used to create the `<tbody>` containing the table rows. @property TBODY_TEMPLATE @type {HTML} @default '<tbody class="{className}">{content}</tbody>' @since 3.6.0 **/ TBODY_TEMPLATE: '<tbody class="{className}"></tbody>', // -- Public methods ------------------------------------------------------ /** Returns the `<td>` Node from the given row and column index. Alternately, the `seed` can be a Node. If so, the nearest ancestor cell is returned. If the `seed` is a cell, it is returned. If there is no cell at the given coordinates, `null` is returned. Optionally, include an offset array or string to return a cell near the cell identified by the `seed`. The offset can be an array containing the number of rows to shift followed by the number of columns to shift, or one of "above", "below", "next", or "previous". <pre><code>// Previous cell in the previous row var cell = table.getCell(e.target, [-1, -1]); // Next cell var cell = table.getCell(e.target, 'next'); var cell = table.getCell(e.taregt, [0, 1];</pre></code> @method getCell @param {Number[]|Node} seed Array of row and column indexes, or a Node that is either the cell itself or a descendant of one. @param {Number[]|String} [shift] Offset by which to identify the returned cell Node @return {Node} @since 3.5.0 **/ getCell: function (seed, shift) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "getCell", 200); _yuitest_coverline("build/datatable-body/datatable-body.js", 201); var tbody = this.tbodyNode, row, cell, index, rowIndexOffset; _yuitest_coverline("build/datatable-body/datatable-body.js", 204); if (seed && tbody) { _yuitest_coverline("build/datatable-body/datatable-body.js", 205); if (isArray(seed)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 206); row = tbody.get('children').item(seed[0]); _yuitest_coverline("build/datatable-body/datatable-body.js", 207); cell = row && row.get('children').item(seed[1]); } else {_yuitest_coverline("build/datatable-body/datatable-body.js", 208); if (Y.instanceOf(seed, Y.Node)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 209); cell = seed.ancestor('.' + this.getClassName('cell'), true); }} _yuitest_coverline("build/datatable-body/datatable-body.js", 212); if (cell && shift) { _yuitest_coverline("build/datatable-body/datatable-body.js", 213); rowIndexOffset = tbody.get('firstChild.rowIndex'); _yuitest_coverline("build/datatable-body/datatable-body.js", 214); if (isString(shift)) { // TODO this should be a static object map _yuitest_coverline("build/datatable-body/datatable-body.js", 216); switch (shift) { case 'above' : _yuitest_coverline("build/datatable-body/datatable-body.js", 217); shift = [-1, 0]; break; case 'below' : _yuitest_coverline("build/datatable-body/datatable-body.js", 218); shift = [1, 0]; break; case 'next' : _yuitest_coverline("build/datatable-body/datatable-body.js", 219); shift = [0, 1]; break; case 'previous': _yuitest_coverline("build/datatable-body/datatable-body.js", 220); shift = [0, -1]; break; } } _yuitest_coverline("build/datatable-body/datatable-body.js", 224); if (isArray(shift)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 225); index = cell.get('parentNode.rowIndex') + shift[0] - rowIndexOffset; _yuitest_coverline("build/datatable-body/datatable-body.js", 227); row = tbody.get('children').item(index); _yuitest_coverline("build/datatable-body/datatable-body.js", 229); index = cell.get('cellIndex') + shift[1]; _yuitest_coverline("build/datatable-body/datatable-body.js", 230); cell = row && row.get('children').item(index); } } } _yuitest_coverline("build/datatable-body/datatable-body.js", 235); return cell || null; }, /** Returns the generated CSS classname based on the input. If the `host` attribute is configured, it will attempt to relay to its `getClassName` or use its static `NAME` property as a string base. If `host` is absent or has neither method nor `NAME`, a CSS classname will be generated using this class's `NAME`. @method getClassName @param {String} token* Any number of token strings to assemble the classname from. @return {String} @protected @since 3.5.0 **/ getClassName: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "getClassName", 253); _yuitest_coverline("build/datatable-body/datatable-body.js", 254); var host = this.host, args; _yuitest_coverline("build/datatable-body/datatable-body.js", 257); if (host && host.getClassName) { _yuitest_coverline("build/datatable-body/datatable-body.js", 258); return host.getClassName.apply(host, arguments); } else { _yuitest_coverline("build/datatable-body/datatable-body.js", 260); args = toArray(arguments); _yuitest_coverline("build/datatable-body/datatable-body.js", 261); args.unshift(this.constructor.NAME); _yuitest_coverline("build/datatable-body/datatable-body.js", 262); return Y.ClassNameManager.getClassName .apply(Y.ClassNameManager, args); } }, /** Returns the Model associated to the row Node or id provided. Passing the Node or id for a descendant of the row also works. If no Model can be found, `null` is returned. @method getRecord @param {String|Node} seed Row Node or `id`, or one for a descendant of a row @return {Model} @since 3.5.0 **/ getRecord: function (seed) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "getRecord", 278); _yuitest_coverline("build/datatable-body/datatable-body.js", 279); var modelList = this.get('modelList'), tbody = this.tbodyNode, row = null, record; _yuitest_coverline("build/datatable-body/datatable-body.js", 284); if (tbody) { _yuitest_coverline("build/datatable-body/datatable-body.js", 285); if (isString(seed)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 286); seed = tbody.one('#' + seed); } _yuitest_coverline("build/datatable-body/datatable-body.js", 289); if (Y.instanceOf(seed, Y.Node)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 290); row = seed.ancestor(function (node) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "(anonymous 2)", 290); _yuitest_coverline("build/datatable-body/datatable-body.js", 291); return node.get('parentNode').compareTo(tbody); }, true); _yuitest_coverline("build/datatable-body/datatable-body.js", 294); record = row && modelList.getByClientId(row.getData('yui3-record')); } } _yuitest_coverline("build/datatable-body/datatable-body.js", 299); return record || null; }, /** Returns the `<tr>` Node from the given row index, Model, or Model's `clientId`. If the rows haven't been rendered yet, or if the row can't be found by the input, `null` is returned. @method getRow @param {Number|String|Model} id Row index, Model instance, or clientId @return {Node} @since 3.5.0 **/ getRow: function (id) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "getRow", 312); _yuitest_coverline("build/datatable-body/datatable-body.js", 313); var tbody = this.tbodyNode, row = null; _yuitest_coverline("build/datatable-body/datatable-body.js", 316); if (tbody) { _yuitest_coverline("build/datatable-body/datatable-body.js", 317); if (id) { _yuitest_coverline("build/datatable-body/datatable-body.js", 318); id = this._idMap[id.get ? id.get('clientId') : id] || id; } _yuitest_coverline("build/datatable-body/datatable-body.js", 321); row = isNumber(id) ? tbody.get('children').item(id) : tbody.one('#' + id); } _yuitest_coverline("build/datatable-body/datatable-body.js", 326); return row; }, /** Creates the table's `<tbody>` content by assembling markup generated by populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content from the `columns` and `modelList` attributes. The rendering process happens in three stages: 1. A row template is assembled from the `columns` attribute (see `_createRowTemplate`) 2. An HTML string is built up by concatening the application of the data in each Model in the `modelList` to the row template. For cells with `formatter`s, the function is called to generate cell content. Cells with `nodeFormatter`s are ignored. For all other cells, the data value from the Model attribute for the given column key is used. The accumulated row markup is then inserted into the container. 3. If any column is configured with a `nodeFormatter`, the `modelList` is iterated again to apply the `nodeFormatter`s. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @method render @return {BodyView} The instance @chainable @since 3.5.0 **/ render: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "render", 419); _yuitest_coverline("build/datatable-body/datatable-body.js", 420); var table = this.get('container'), data = this.get('modelList'), columns = this.get('columns'), tbody = this.tbodyNode || (this.tbodyNode = this._createTBodyNode()); // Needed for mutation _yuitest_coverline("build/datatable-body/datatable-body.js", 427); this._createRowTemplate(columns); _yuitest_coverline("build/datatable-body/datatable-body.js", 429); if (data) { _yuitest_coverline("build/datatable-body/datatable-body.js", 430); tbody.setHTML(this._createDataHTML(columns)); _yuitest_coverline("build/datatable-body/datatable-body.js", 432); this._applyNodeFormatters(tbody, columns); } _yuitest_coverline("build/datatable-body/datatable-body.js", 435); if (tbody.get('parentNode') !== table) { _yuitest_coverline("build/datatable-body/datatable-body.js", 436); table.appendChild(tbody); } _yuitest_coverline("build/datatable-body/datatable-body.js", 439); this.bindUI(); _yuitest_coverline("build/datatable-body/datatable-body.js", 441); return this; }, // -- Protected and private methods --------------------------------------- /** Handles changes in the source's columns attribute. Redraws the table data. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ // TODO: Preserve existing DOM // This will involve parsing and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function (e) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_afterColumnsChange", 460); _yuitest_coverline("build/datatable-body/datatable-body.js", 461); this.render(); }, /** Handles modelList changes, including additions, deletions, and updates. Modifies the existing table DOM accordingly. @method _afterDataChange @param {EventFacade} e The `change` event from the ModelList @protected @since 3.5.0 **/ _afterDataChange: function (e) { //var type = e.type.slice(e.type.lastIndexOf(':') + 1); // TODO: Isolate changes _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_afterDataChange", 474); _yuitest_coverline("build/datatable-body/datatable-body.js", 478); this.render(); }, /** Handles replacement of the modelList. Rerenders the `<tbody>` contents. @method _afterModelListChange @param {EventFacade} e The `modelListChange` event @protected @since 3.6.0 **/ _afterModelListChange: function (e) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_afterModelListChange", 491); _yuitest_coverline("build/datatable-body/datatable-body.js", 492); var handles = this._eventHandles; _yuitest_coverline("build/datatable-body/datatable-body.js", 494); if (handles.dataChange) { _yuitest_coverline("build/datatable-body/datatable-body.js", 495); handles.dataChange.detach(); _yuitest_coverline("build/datatable-body/datatable-body.js", 496); delete handles.dataChange; _yuitest_coverline("build/datatable-body/datatable-body.js", 497); this.bindUI(); } _yuitest_coverline("build/datatable-body/datatable-body.js", 500); if (this.tbodyNode) { _yuitest_coverline("build/datatable-body/datatable-body.js", 501); this.render(); } }, /** Iterates the `modelList`, and calls any `nodeFormatter`s found in the `columns` param on the appropriate cell Nodes in the `tbody`. @method _applyNodeFormatters @param {Node} tbody The `<tbody>` Node whose columns to update @param {Object[]} columns The column configurations @protected @since 3.5.0 **/ _applyNodeFormatters: function (tbody, columns) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_applyNodeFormatters", 515); _yuitest_coverline("build/datatable-body/datatable-body.js", 516); var host = this.host, data = this.get('modelList'), formatters = [], linerQuery = '.' + this.getClassName('liner'), rows, i, len; // Only iterate the ModelList again if there are nodeFormatters _yuitest_coverline("build/datatable-body/datatable-body.js", 523); for (i = 0, len = columns.length; i < len; ++i) { _yuitest_coverline("build/datatable-body/datatable-body.js", 524); if (columns[i].nodeFormatter) { _yuitest_coverline("build/datatable-body/datatable-body.js", 525); formatters.push(i); } } _yuitest_coverline("build/datatable-body/datatable-body.js", 529); if (data && formatters.length) { _yuitest_coverline("build/datatable-body/datatable-body.js", 530); rows = tbody.get('childNodes'); _yuitest_coverline("build/datatable-body/datatable-body.js", 532); data.each(function (record, index) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "(anonymous 3)", 532); _yuitest_coverline("build/datatable-body/datatable-body.js", 533); var formatterData = { data : record.toJSON(), record : record, rowIndex : index }, row = rows.item(index), i, len, col, key, cells, cell, keep; _yuitest_coverline("build/datatable-body/datatable-body.js", 542); if (row) { _yuitest_coverline("build/datatable-body/datatable-body.js", 543); cells = row.get('childNodes'); _yuitest_coverline("build/datatable-body/datatable-body.js", 544); for (i = 0, len = formatters.length; i < len; ++i) { _yuitest_coverline("build/datatable-body/datatable-body.js", 545); cell = cells.item(formatters[i]); _yuitest_coverline("build/datatable-body/datatable-body.js", 547); if (cell) { _yuitest_coverline("build/datatable-body/datatable-body.js", 548); col = formatterData.column = columns[formatters[i]]; _yuitest_coverline("build/datatable-body/datatable-body.js", 549); key = col.key || col.id; _yuitest_coverline("build/datatable-body/datatable-body.js", 551); formatterData.value = record.get(key); _yuitest_coverline("build/datatable-body/datatable-body.js", 552); formatterData.td = cell; _yuitest_coverline("build/datatable-body/datatable-body.js", 553); formatterData.cell = cell.one(linerQuery) || cell; _yuitest_coverline("build/datatable-body/datatable-body.js", 555); keep = col.nodeFormatter.call(host,formatterData); _yuitest_coverline("build/datatable-body/datatable-body.js", 557); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. _yuitest_coverline("build/datatable-body/datatable-body.js", 563); cell.destroy(true); } } } } }); } }, /** Binds event subscriptions from the UI and the host (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "bindUI", 579); _yuitest_coverline("build/datatable-body/datatable-body.js", 580); var handles = this._eventHandles, modelList = this.get('modelList'), changeEvent = modelList.model.NAME + ':change'; _yuitest_coverline("build/datatable-body/datatable-body.js", 584); if (!handles.columnsChange) { _yuitest_coverline("build/datatable-body/datatable-body.js", 585); handles.columnsChange = this.after('columnsChange', bind('_afterColumnsChange', this)); } _yuitest_coverline("build/datatable-body/datatable-body.js", 589); if (modelList && !handles.dataChange) { _yuitest_coverline("build/datatable-body/datatable-body.js", 590); handles.dataChange = modelList.after( ['add', 'remove', 'reset', changeEvent], bind('_afterDataChange', this)); } }, /** Iterates the `modelList` and applies each Model to the `_rowTemplate`, allowing any column `formatter` or `emptyCellValue` to override cell content for the appropriate column. The aggregated HTML string is returned. @method _createDataHTML @param {Object[]} columns The column configurations to customize the generated cell content or class names @return {HTML} The markup for all Models in the `modelList`, each applied to the `_rowTemplate` @protected @since 3.5.0 **/ _createDataHTML: function (columns) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_createDataHTML", 610); _yuitest_coverline("build/datatable-body/datatable-body.js", 611); var data = this.get('modelList'), html = ''; _yuitest_coverline("build/datatable-body/datatable-body.js", 614); if (data) { _yuitest_coverline("build/datatable-body/datatable-body.js", 615); data.each(function (model, index) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "(anonymous 4)", 615); _yuitest_coverline("build/datatable-body/datatable-body.js", 616); html += this._createRowHTML(model, index, columns); }, this); } _yuitest_coverline("build/datatable-body/datatable-body.js", 620); return html; }, /** Applies the data of a given Model, modified by any column formatters and supplemented by other template values to the instance's `_rowTemplate` (see `_createRowTemplate`). The generated string is then returned. The data from Model's attributes is fetched by `toJSON` and this data object is appended with other properties to supply values to {placeholders} in the template. For a template generated from a Model with 'foo' and 'bar' attributes, the data object would end up with the following properties before being used to populate the `_rowTemplate`: * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute. * `foo` - The value to populate the 'foo' column cell content. This value will be the value stored in the Model's `foo` attribute, or the result of the column's `formatter` if assigned. If the value is '', `null`, or `undefined`, and the column's `emptyCellValue` is assigned, that value will be used. * `bar` - Same for the 'bar' column cell content. * `foo-className` - String of CSS classes to apply to the `<td>`. * `bar-className` - Same. * `rowClass` - String of CSS classes to apply to the `<tr>`. This will be the odd/even class per the specified index plus any additional classes assigned by column formatters (via `o.rowClass`). Because this object is available to formatters, any additional properties can be added to fill in custom {placeholders} in the `_rowTemplate`. @method _createRowHTML @param {Model} model The Model instance to apply to the row template @param {Number} index The index the row will be appearing @param {Object[]} columns The column configurations @return {HTML} The markup for the provided Model, less any `nodeFormatter`s @protected @since 3.5.0 **/ _createRowHTML: function (model, index, columns) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_createRowHTML", 658); _yuitest_coverline("build/datatable-body/datatable-body.js", 659); var data = model.toJSON(), clientId = model.get('clientId'), values = { rowId : this._getRowId(clientId), clientId: clientId, rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN }, host = this.host || this, i, len, col, token, value, formatterData; _yuitest_coverline("build/datatable-body/datatable-body.js", 669); for (i = 0, len = columns.length; i < len; ++i) { _yuitest_coverline("build/datatable-body/datatable-body.js", 670); col = columns[i]; _yuitest_coverline("build/datatable-body/datatable-body.js", 671); value = data[col.key]; _yuitest_coverline("build/datatable-body/datatable-body.js", 672); token = col._id || col.key; _yuitest_coverline("build/datatable-body/datatable-body.js", 674); values[token + '-className'] = ''; _yuitest_coverline("build/datatable-body/datatable-body.js", 676); if (col.formatter) { _yuitest_coverline("build/datatable-body/datatable-body.js", 677); formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; _yuitest_coverline("build/datatable-body/datatable-body.js", 687); if (typeof col.formatter === 'string') { _yuitest_coverline("build/datatable-body/datatable-body.js", 688); if (value !== undefined) { // TODO: look for known formatters by string name _yuitest_coverline("build/datatable-body/datatable-body.js", 690); value = fromTemplate(col.formatter, formatterData); } } else { // Formatters can either return a value _yuitest_coverline("build/datatable-body/datatable-body.js", 694); value = col.formatter.call(host, formatterData); // or update the value property of the data obj passed _yuitest_coverline("build/datatable-body/datatable-body.js", 697); if (value === undefined) { _yuitest_coverline("build/datatable-body/datatable-body.js", 698); value = formatterData.value; } _yuitest_coverline("build/datatable-body/datatable-body.js", 701); values[token + '-className'] = formatterData.className; _yuitest_coverline("build/datatable-body/datatable-body.js", 702); values.rowClass += ' ' + formatterData.rowClass; } } _yuitest_coverline("build/datatable-body/datatable-body.js", 706); if (value === undefined || value === null || value === '') { _yuitest_coverline("build/datatable-body/datatable-body.js", 707); value = col.emptyCellValue || ''; } _yuitest_coverline("build/datatable-body/datatable-body.js", 710); values[token] = col.allowHTML ? value : htmlEscape(value); _yuitest_coverline("build/datatable-body/datatable-body.js", 712); values.rowClass = values.rowClass.replace(/\s+/g, ' '); } _yuitest_coverline("build/datatable-body/datatable-body.js", 715); return fromTemplate(this._rowTemplate, values); }, /** Creates a custom HTML template string for use in generating the markup for individual table rows with {placeholder}s to capture data from the Models in the `modelList` attribute or from column `formatter`s. Assigns the `_rowTemplate` property. @method _createRowTemplate @param {Object[]} columns Array of column configuration objects @protected @since 3.5.0 **/ _createRowTemplate: function (columns) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_createRowTemplate", 730); _yuitest_coverline("build/datatable-body/datatable-body.js", 731); var html = '', cellTemplate = this.CELL_TEMPLATE, i, len, col, key, token, headers, tokenValues; _yuitest_coverline("build/datatable-body/datatable-body.js", 735); for (i = 0, len = columns.length; i < len; ++i) { _yuitest_coverline("build/datatable-body/datatable-body.js", 736); col = columns[i]; _yuitest_coverline("build/datatable-body/datatable-body.js", 737); key = col.key; _yuitest_coverline("build/datatable-body/datatable-body.js", 738); token = col._id || key; // Only include headers if there are more than one _yuitest_coverline("build/datatable-body/datatable-body.js", 740); headers = (col._headers || []).length > 1 ? 'headers="' + col._headers.join(' ') + '"' : ''; _yuitest_coverline("build/datatable-body/datatable-body.js", 743); tokenValues = { content : '{' + token + '}', headers : headers, className: this.getClassName('col', token) + ' ' + (col.className || '') + ' ' + this.getClassName('cell') + ' {' + token + '-className}' }; _yuitest_coverline("build/datatable-body/datatable-body.js", 752); if (col.nodeFormatter) { // Defer all node decoration to the formatter _yuitest_coverline("build/datatable-body/datatable-body.js", 754); tokenValues.content = ''; } _yuitest_coverline("build/datatable-body/datatable-body.js", 757); html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues); } _yuitest_coverline("build/datatable-body/datatable-body.js", 760); this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, { content: html }); }, /** Creates the `<tbody>` node that will store the data rows. @method _createTBodyNode @return {Node} @protected @since 3.6.0 **/ _createTBodyNode: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_createTBodyNode", 773); _yuitest_coverline("build/datatable-body/datatable-body.js", 774); return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, { className: this.getClassName('data') })); }, /** Destroys the instance. @method destructor @protected @since 3.5.0 **/ destructor: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "destructor", 786); _yuitest_coverline("build/datatable-body/datatable-body.js", 787); (new Y.EventHandle(YObject.values(this._eventHandles))).detach(); }, /** Holds the event subscriptions needing to be detached when the instance is `destroy()`ed. @property _eventHandles @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_eventHandles: null, /** Returns the row ID associated with a Model's clientId. @method _getRowId @param {String} clientId The Model clientId @return {String} @protected **/ _getRowId: function (clientId) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_getRowId", 810); _yuitest_coverline("build/datatable-body/datatable-body.js", 811); return this._idMap[clientId] || (this._idMap[clientId] = Y.guid()); }, /** Map of Model clientIds to row ids. @property _idMap @type {Object} @protected **/ //_idMap, /** Initializes the instance. Reads the following configuration properties in addition to the instance attributes: * `columns` - (REQUIRED) The initial column information * `host` - The object to serve as source of truth for column info and for generating class names @method initializer @param {Object} config Configuration data @protected @since 3.5.0 **/ initializer: function (config) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "initializer", 836); _yuitest_coverline("build/datatable-body/datatable-body.js", 837); this.host = config.host; _yuitest_coverline("build/datatable-body/datatable-body.js", 839); this._eventHandles = { modelListChange: this.after('modelListChange', bind('_afterModelListChange', this)) }; _yuitest_coverline("build/datatable-body/datatable-body.js", 843); this._idMap = {}; _yuitest_coverline("build/datatable-body/datatable-body.js", 845); this.CLASS_ODD = this.getClassName('odd'); _yuitest_coverline("build/datatable-body/datatable-body.js", 846); this.CLASS_EVEN = this.getClassName('even'); } /** The HTML template used to create a full row of markup for a single Model in the `modelList` plus any customizations defined in the column configurations. @property _rowTemplate @type {HTML} @default (initially unset) @protected @since 3.5.0 **/ //_rowTemplate: null }); }, '@VERSION@', {"requires": ["datatable-core", "view", "classnamemanager"]});
src/components/Footer/Footer.js
zsu13579/whatsgoinontonight
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Footer.css'; import Link from '../Link'; class Footer extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© LV.com</span> </div> </div> ); } } export default withStyles(s)(Footer);
src/react.js
boneyao/redux
import React from 'react'; import createAll from './components/createAll'; export const { Provider, Connector, provide, connect } = createAll(React);
blueocean-material-icons/src/js/components/svg-icons/av/play-arrow.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvPlayArrow = (props) => ( <SvgIcon {...props}> <path d="M8 5v14l11-7z"/> </SvgIcon> ); AvPlayArrow.displayName = 'AvPlayArrow'; AvPlayArrow.muiName = 'SvgIcon'; export default AvPlayArrow;
src/containers/MiscContainer/MiscContainer.js
anvk/redux-portal-boilerplate
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Misc } from '../../components'; class MiscContainer extends Component { render() { return <Misc {...this.props} />; } } function mapStateToProps(state) { return { emojis: state.shared.emojis, gitignoreTemplates: state.shared.gitignoreTemplates }; } export default connect(mapStateToProps)(MiscContainer);
app/components/layout/newProject/types/website.js
communicode-source/communicode
import React from 'react'; import PropTypes from 'prop-types'; function handleTypeSelect(e, selectProjectType) { if(e.target.value === 'Select...') { return selectProjectType(''); } return selectProjectType(e.target.value); } const Website = ({ selectProjectType, type }) => ( <div> <select value={(type === '') ? 'Select a Type' : type} onChange={(e) => { handleTypeSelect(e, selectProjectType); }} name="type"> <option value={null}>Select a Type...</option> <option value="SplashPage">Splash Page (Volunteer)</option> <option value="MultiplePageStaticWebsite">Multiple Page Static Website ($50)</option> <option value="WebsiteWithABlog">Blog Website ($75)</option> <option value="WebsiteWithMultipleContentSources">Multiple Pages with Dynamic Content ($150)</option> <option value="UserAccountWebsite">User Account Website ($500)</option> <option value="ECommerceWebsite">E-Commerce Website ($2,000)</option> </select> </div> ); Website.propTypes = { selectProjectType: PropTypes.func, type: PropTypes.string }; export default Website;
src/components/panel/Panel.js
tyleranton/dashboard
import React from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import { DragSource, DropTarget } from 'react-dnd'; import flow from 'lodash/flow'; import styled from 'styled-components'; const panelSrc = { beginDrag(props) { return { id: props.id, index: props.index }; } }; const panelTarget = { hover(props, monitor, component) { const dragIndex = monitor.getItem().index; const hoverIndex = props.index; if (dragIndex === hoverIndex) return; const hoverBoundingRect = findDOMNode(component).getBoundingClientRect(); const hoverMiddleX = (hoverBoundingRect.right - hoverBoundingRect.left) / 2; const clientOffset = monitor.getClientOffset(); const hoverClientX = clientOffset.x - hoverBoundingRect.left; if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) { return; } if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) { return; } props.movePanel(dragIndex, hoverIndex); monitor.getItem().index = hoverIndex; } }; const collect = connect => { return { connectDragSource: connect.dragSource(), connectDragPreview: connect.dragPreview() }; }; /** * HOC providing a draggable/resizable panel * @param {React.Component} Plugin - Your plugin component * @param {Object} [config] - Config object for width, height, background color, and resize options. */ const createPanel = (Plugin, config) => { class Panel extends React.Component { static propTypes = { connectDragSource: PropTypes.func.isRequired, connectDropTarget: PropTypes.func.isRequired, index: PropTypes.number.isRequired, id: PropTypes.any.isRequired, movePanel: PropTypes.func.isRequired }; Container = styled.div` padding: 1%; width: ${config && config.width ? config.width : '250px'}; height: ${config && config.height ? config.height : '400px'}; margin-left: 1%; margin-top: 1%; background-color: ${config && config.bgColor ? config.bgColor : '#333333'}; text-align: center; overflow: hidden; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); transition: all 0.3s cubic-bezier(.25, .8, .25, 1); &:active { resize: ${config && config.resize ? config.resize : 'none'}; box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22); } &:hover { resize: ${config && config.resize ? 'both' : 'none'}; } `; Draggable = styled.div` cursor: move; text-align: right; `; render() { const { connectDragSource, connectDragPreview, connectDropTarget } = this.props; return ( <this.Container ref={instance => { const node = findDOMNode(instance); connectDragPreview(node); connectDropTarget(node); }} > <this.Draggable ref={instance => { const node = findDOMNode(instance); connectDragSource(node); }} > <i className="fa fa-bars" /> </this.Draggable> <Plugin /> </this.Container> ); } } return flow( DropTarget('panel', panelTarget, connect => ({ connectDropTarget: connect.dropTarget() })), DragSource('panel', panelSrc, collect) )(Panel); }; export default createPanel;
packages/material-ui-icons/lib/esm/NoPhotographyOutlined.js
mbrookes/material-ui
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M8.9 6.07 7.48 4.66 9 3h6l1.83 2H20c1.1 0 2 .9 2 2v12c0 .05-.01.1-.02.16L20 17.17V7h-4.05l-1.83-2H9.88L8.9 6.07zm11.59 17.24L18.17 21H4c-1.1 0-2-.9-2-2V7c0-.59.27-1.12.68-1.49l-2-2L2.1 2.1l19.8 19.8-1.41 1.41zM9.19 12.02c-.11.31-.19.63-.19.98 0 1.66 1.34 3 3 3 .35 0 .67-.08.98-.19l-3.79-3.79zM16.17 19l-1.68-1.68c-.73.43-1.58.68-2.49.68-2.76 0-5-2.24-5-5 0-.91.25-1.76.68-2.49L4.17 7H4v12h12.17zm-1.36-7.02 2.07 2.07c.08-.34.12-.69.12-1.05 0-2.76-2.24-5-5-5-.36 0-.71.04-1.06.12l2.07 2.07c.84.3 1.5.96 1.8 1.79z" }), 'NoPhotographyOutlined');
src/svg-icons/image/music-note.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageMusicNote = (props) => ( <SvgIcon {...props}> <path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/> </SvgIcon> ); ImageMusicNote = pure(ImageMusicNote); ImageMusicNote.displayName = 'ImageMusicNote'; ImageMusicNote.muiName = 'SvgIcon'; export default ImageMusicNote;
js/components/TaskRow/TaskRow.js
amostap/react-native-todo
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text, TouchableOpacity } from 'react-native'; import MaterialIcon from 'react-native-vector-icons/MaterialIcons'; import OcticonsIcon from 'react-native-vector-icons/Octicons'; import styles from './styles'; import globalStyles from '../../globalStyles'; const TaskRow = ({ todo, onDone, onUndone, onDelete }) => { const { doneContainer, container, text, doneText, buttonContainer } = styles; return ( <View style={[container, todo.state === 'done' && doneContainer]}> <View style={buttonContainer}> { todo.state === 'done' ? ( <TouchableOpacity onPress={() => onUndone(todo)} > <MaterialIcon color={globalStyles.colors.green} name="check" size={28} /> </TouchableOpacity> ) : ( <TouchableOpacity onPress={() => onDone(todo)} > <MaterialIcon color={globalStyles.colors.red} name="radio-button-unchecked" size={28} /> </TouchableOpacity> ) } </View> <Text style={[text, todo.state === 'done' && doneText]}> { todo.task } </Text> <View style={buttonContainer}> <TouchableOpacity onPress={() => onDelete(todo)} > <OcticonsIcon color={globalStyles.colors.yellow} name="trashcan" size={20} /> </TouchableOpacity> </View> </View> ); }; TaskRow.propTypes = { onDone: PropTypes.func.isRequired, onUndone: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, todo: PropTypes.shape({ task: PropTypes.string.isRequired, state: PropTypes.string.isRequired, }).isRequired, }; export default TaskRow;
src/containers/Quiz/Question.js
AbhishekCode/quiz
import React, { Component } from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { StyleSheet, css } from 'aphrodite'; import RaisedButton from 'material-ui/RaisedButton'; import Divider from 'material-ui/Divider'; import {getWidth, getHeight} from '../../utils/config' class Question extends Component { constructor(props) { super(props); }; _selectAnswer = (index) => { let answeredOption = index + 1; // zero index +1 if(answeredOption == this.props.question.answer) { this.props.onAnswered(index, true); }else { this.props.onAnswered(index , false); } }; render() { const {question} = this.props; const questionText = question ? question.question : "not loaded"; return ( <div className={css(styles.container)}> <span className={css(styles.question)}>{questionText}</span> {question.imageURL && <img src={question.imageURL} style={imageStyle} />} <div className={css(styles.optionContainer)}> { question.options.map((option, index) => this._renderOption(option, index)) } </div> <Divider /> </div> ); }; _renderOption = (option,index) => { const correctAnswer = (index+1 == this.props.question.answer && this.props.answered) ? true : false; const wrongAnswer = (this.props.answered && !correctAnswer && index == this.props.answeredIndex) ? true : false; return ( <RaisedButton label={option} style={optionStyle} primary={correctAnswer} secondary={wrongAnswer} onClick={()=>this._selectAnswer(index)} /> ); }; } const optionStyle = { display: 'flex', flex:1, flexDirection: 'row', justyfyContent: 'center', alignItems: 'center', margin: 10 } const imageStyle = { width: 'auto', maxWidth: '100%', height: 'auto', maxHeight: 300, } const styles = StyleSheet.create({ container: { display: 'flex', flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between' }, question :{ padding: 20, }, optionContainer: { display: 'flex', flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between' } }); export default Question;
modules/__tests__/History-test.js
batmanimal/react-router
/*eslint-env mocha */ import expect from 'expect' import React from 'react' import History from '../History' import Router from '../Router' import Route from '../Route' import createHistory from 'history/lib/createMemoryHistory' describe('History Mixin', function () { let node beforeEach(function () { node = document.createElement('div') }) afterEach(function () { React.unmountComponentAtNode(node) }) it('assigns the history to the component instance', function (done) { let history = createHistory('/') function assertHistory() { expect(this.history).toExist() } let Component = React.createClass({ mixins: [ History ], componentWillMount: assertHistory, render () { return null } }) React.render(( <Router history={history}> <Route path="/" component={Component} /> </Router> ), node, done) }) })
files/maxmertkit/1.0.0/js/maxmertkit.min.js
cedricbousmanne/jsdelivr
(function(){var e,t,n,r,i,s,o;r=[];s=[];i={x:0,y:0,z:0};o="0.0.1";e=function(){function e(e){this.name=e}e.prototype.callbacks=r;e.prototype.registerCallback=function(e){return this.callbacks.push(e)};return e}();n=function(){function t(){}t.prototype.events=s;t.prototype.registerEvent=function(t){var n;n=new e(t);return this.events[t]=n};t.prototype.dispatchEvent=function(e,t){var n,r,i,s,o;s=this.events[e].callbacks;o=[];for(r=0,i=s.length;r<i;r++){n=s[r];o.push(n(t))}return o};t.prototype.addEventListener=function(e,t){return this.events[e].registerCallback(t)};return t}();t=function(){function e(e,t){this.$btn=e;this.options=t;this._pushInstance();if(this._afterConstruct!=null){this._afterConstruct()}}e.prototype._id=0;e.prototype._instances=new Array;e.prototype.destroy=function(){this.$el.off("."+this._name);return this._popInstance()};e.prototype._extend=function(e,t){var n,r;for(n in t){r=t[n];e[n]=r}return e};e.prototype._merge=function(e,t){return this._extend(this._extend({},e),t)};e.prototype._setOptions=function(e){return console.warning("Maxmertkit Helpers. There is no standart setOptions function.")};e.prototype._pushInstance=function(){this._id++;return this._instances.push(this)};e.prototype._popInstance=function(){var e,t,n,r,i,s;i=this._instances;s=[];for(e=n=0,r=i.length;n<r;e=++n){t=i[e];if(t._id===this._id){this._instances.splice(e,1)}s.push(delete this)}return s};e.prototype._selfish=function(){var e,t,n,r,i,s;i=this._instances;s=[];for(e=n=0,r=i.length;n<r;e=++n){t=i[e];if(this._id!==t._id){s.push(t.close())}else{s.push(void 0)}}return s};e.prototype._getVersion=function(){return o};e.prototype.reactor=new n;e.prototype._setTransform=function(e,t){e.webkitTransform=t;e.MozTransform=t;return e.transform=t};e.prototype._equalNodes=function(e,t){return e.get(0)===t.get(0)};e.prototype._deviceMobile=function(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)};e.prototype._refreshSizes=function(){this._windowHeight=$(window).height();this._windowWidth=$(window).width();this._height=this.$el.height();this._width=this.$el.width();if(this.scroll!=null){if(this.scroll[0].nodeName==="BODY"){return this._offset=this.$el.offset()}else{return this._offset=this.$el.offset()}}else{return this._offset=this.$el.offset()}};e.prototype._getContainer=function(e){var t,n;t=e[0]||e;while(t=t.parentNode){try{n=getComputedStyle(t)}catch(r){}if(n==null){return $(t)}if(/(relative)/.test(n["position"])||t!=null&&t.style!=null&&/(relative)/.test(t.style["position"])){return $(t)}}return $(document)};e.prototype._getScrollParent=function(e){var t,n;t=e[0]||e;while(t=t.parentNode){try{n=getComputedStyle(t)}catch(r){}if(n==null){return $(t)}if(/(auto|scroll)/.test(n["overflow"]+n["overflow-y"]+n["overflow-x"])&&$(t)[0].nodeName!=="BODY"){return $(t)}}return $(document)};e.prototype._isVisible=function(){return this._offset.top-this._windowHeight<=this.scroll.scrollTop()&&this.scroll.scrollTop()<=this._offset.top+this._height};e.prototype._getVisiblePercent=function(){var e,t,n;n=this._offset.top;e=this.scroll.scrollTop();t=this._offset.top+this._height;return(e-n)/(t-n)};e.prototype._scrollVisible=function(){var e,t,n,r;if(this.scroll!=null){n=this._offset.top-this._windowHeight;t=this._offset.top+this._height+this._windowHeight;e=this.scroll.scrollTop()+this._windowHeight;r=1-e/t;return 1>r&&r>0}else{return true}};e.prototype._setGlobalRotation=function(e,t,n){return i={x:e,y:t,z:n}};e.prototype._getGlobalRotation=function(){return i};return e}();(function(){var e,t,n;e=jQuery.event.special;t="D"+ +(new Date);n="D"+(+(new Date)+1);e.scrollstart={setup:function(){var n,r;r=void 0;n=function(t){var n;n=arguments;if(r){clearTimeout(r)}else{t.type="scrollstart";jQuery.event.trigger.apply(this,n)}r=setTimeout(function(){r=null},e.scrollstop.latency)};jQuery(this).bind("scroll",n).data(t,n)},teardown:function(){jQuery(this).unbind("scroll",jQuery(this).data(t))}};e.scrollstop={latency:300,setup:function(){var t,r;r=void 0;t=function(t){var n;n=arguments;if(r){clearTimeout(r)}r=setTimeout(function(){r=null;t.type="scrollstop";jQuery.event.trigger.apply(this,n)},e.scrollstop.latency)};jQuery(this).bind("scroll",t).data(n,t)},teardown:function(){jQuery(this).unbind("scroll",jQuery(this).data(n))}}})();window["MaxmertkitHelpers"]=t}).call(this);(function(){var e,t,n,r,i,s,o,u,a,f,l={}.hasOwnProperty,c=function(e,t){function r(){this.constructor=e}for(var n in t){if(l.call(t,n))e[n]=t[n]}r.prototype=t.prototype;e.prototype=new r;e.__super__=t.prototype;return e};s="affix";i=[];r=0;e=function(e){function o(e,t){var n;this.el=e;this.options=t;this.$el=$(this.el);this.$el.parent().append("&nbsp;");this._id=r++;n={spy:this.$el.data("spy")||"affix",offset:5,beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}};this.options=this._merge(n,this.options);this.beforeactive=this.options.beforeactive;this.onactive=this.options.onactive;this.beforeunactive=this.options.beforeunactive;this.onunactive=this.options.onunactive;this.start();o.__super__.constructor.call(this,this.$btn,this.options)}c(o,e);o.prototype._name=s;o.prototype._instances=i;o.prototype._setOptions=function(e){var t,n;for(t in e){n=e[t];if(this.options[t]==null){return console.error("Maxmertkit Affix. You're trying to set unpropriate option.")}this.options[t]=n}};o.prototype.destroy=function(){return o.__super__.destroy.apply(this,arguments)};o.prototype.start=function(){return t.call(this)};o.prototype.stop=function(){return n.call(this)};return o}(MaxmertkitHelpers);u=function(){var e,t;e=this._getContainer(this.$el);if(e[0].firstElementChild.nodeName==="HTML"){t=0}else{t=e.offset().top}if(this.$el.parent()!=null&&this.$el.parent().offset()&&!this._deviceMobile()&&this._windowWidth>992){if(this.$el.parent().offset().top-this.options.offset<=$(document).scrollTop()){if(this.$el.parent().offset().top+e.outerHeight()-this.options.offset-this.$el.outerHeight()>=$(document).scrollTop()){return this.$el.css({width:this.$el.width(),position:"fixed",top:""+this.options.offset+"px",bottom:"auto"})}else{return this.$el.css({position:"absolute",top:"auto",bottom:"-"+this.options.offset+"px",width:this.$el.width()})}}else{this.$el.css("position","relative");return this.$el.css("top","inherit")}}};o=function(){$(document).on("scroll."+this._name+"."+this._id,function(e){return function(t){return u.call(e)}}(this));return $(window).on("resize."+this._name+"."+this._id,function(e){return function(t){e._refreshSizes();if(e._windowWidth<992){e.$el.css("position","relative");return e.$el.css("top","inherit")}else{return u.call(e)}}}(this))};t=function(){var e;if(this.beforeactive!=null){try{e=this.beforeactive.call(this.$el);return e.done(function(e){return function(){return a.call(e)}}(this)).fail(function(e){return function(){return e.$el.trigger("fail."+e._name)}}(this))}catch(t){return a.call(this)}}else{return a.call(this)}};a=function(){this._refreshSizes();o.call(this);this.$el.addClass("_active_");this.$el.trigger("started."+this._name);if(this.onactive!=null){try{return this.onactive.call(this.$el)}catch(e){}}};n=function(){var e;if(this.beforeunactive!=null){try{e=this.beforeunactive.call(this.$el);return e.done(function(e){return function(){return f.call(e)}}(this)).fail(function(e){return function(){return e.$el.trigger("fail."+e._name)}}(this))}catch(t){return f.call(this)}}else{return f.call(this)}};f=function(){this.$el.removeClass("_active_");$(document).off("scroll."+this._name+"."+this._id);this.$el.trigger("stopped."+this._name);if(this.onunactive!=null){try{return this.onunactive.call(this.$el)}catch(e){}}};$.fn[s]=function(t){return this.each(function(){if(!$.data(this,"kit-"+s)){$.data(this,"kit-"+s,new e(this,t))}else{if(typeof t==="object"){$.data(this,"kit-"+s)._setOptions(t)}else{if(typeof t==="string"&&t.charAt(0)!=="_"){$.data(this,"kit-"+s)[t]}}}})}}).call(this);(function(){var e,t,n,r,i,s,o,u,a={}.hasOwnProperty,f=function(e,t){function r(){this.constructor=e}for(var n in t){if(a.call(t,n))e[n]=t[n]}r.prototype=t.prototype;e.prototype=new r;e.__super__=t.prototype;return e};u="button";o=[];s=0;e=function(e){function t(e,n){var r;this.btn=e;this.options=n;this.$btn=$(this.btn);this._id=s++;r={toggle:this.$btn.data("toggle")||"button",group:this.$btn.data("group")||null,type:this.$btn.data("type")||"button",event:"click",beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}};this.options=this._merge(r,this.options);this.beforeactive=this.options.beforeactive;this.onactive=this.options.onactive;this.beforeunactive=this.options.beforeunactive;this.onunactive=this.options.onunactive;this.$btn.on(this.options.event,function(e){return function(){if(!e.$btn.hasClass("_active_")){return e.activate()}else{return e.deactivate()}}}(this));this.$btn.on(this.options.eventClose,function(e){return function(){if(e.options.event!==e.options.eventClose){return e.deactivate()}}}(this));this.$btn.removeClass("_active_ _disabled_ _loading_");t.__super__.constructor.call(this,this.$btn,this.options)}f(t,e);t.prototype._name=u;t.prototype._instances=o;t.prototype._setOptions=function(e){var t,n;for(t in e){n=e[t];if(this.options[t]==null){return console.error("Maxmertkit Button. You're trying to set unpropriate option.")}switch(t){case"event":this.$btn.off(""+this.options.event+"."+this._name);this.options.event=n;this.$btn.on(""+this.options.event+"."+this._name,function(e){return function(){if(e.$btn.hasClass("_active_")){return e.deactivate()}else{return e.activate()}}}(this));break;default:this.options[t]=n;if(typeof n==="function"){this[t]=this.options[t]}}}};t.prototype.destroy=function(){this.$btn.off("."+this._name);return t.__super__.destroy.apply(this,arguments)};t.prototype.activate=function(){return n.call(this)};t.prototype.deactivate=function(){if(this.$btn.hasClass("_active_")){return r.call(this)}};t.prototype.disable=function(){return this.$btn.toggleClass("_disabled_")};return t}(MaxmertkitHelpers);n=function(){var e;if(this.options.selfish){this._selfish()}if(this.beforeactive!=null){try{e=this.beforeactive.call(this.$btn);return e.done(function(e){return function(){return t.call(e)}}(this)).fail(function(e){return function(){return e.$btn.trigger("fail."+e._name)}}(this))}catch(n){return t.call(this)}}else{return t.call(this)}};t=function(){var e,t,n,r;if(this.options.type==="radio"){r=this._instances;for(t=0,n=r.length;t<n;t++){e=r[t];if(this._id!==e._id&&e.options.type==="radio"&&e.options.group===this.options.group){e.deactivate()}}}this.$btn.addClass("_active_");this.$btn.trigger("activated."+this._name);if(this.onactive!=null){try{return this.onactive.call(this.$btn)}catch(i){}}};r=function(){var e;if(this.beforeunactive!=null){try{e=this.beforeunactive.call(this.$btn);return e.done(function(e){return function(){return i.call(e)}}(this)).fail(function(e){return function(){return e.$btn.trigger("fail."+e._name)}}(this))}catch(t){return i.call(this)}}else{return i.call(this)}};i=function(){this.$btn.removeClass("_active_");this.$btn.trigger("deactivated."+this._name);if(this.onunactive!=null){try{return this.onunactive.call(this.$btn)}catch(e){}}};$.fn[u]=function(t){return this.each(function(){if(!$.data(this,"kit-"+u)){$.data(this,"kit-"+u,new e(this,t))}else{if(typeof t==="object"){$.data(this,"kit-"+u)._setOptions(t)}else{if(typeof t==="string"&&t.charAt(0)!=="_"){$.data(this,"kit-"+u)[t]}else{console.error("Maxmertkit Button. You passed into the "+u+" something wrong.\n"+t)}}}})};$(window).on("load",function(){return $('[data-toggle="button"]').each(function(){var e;e=$(this);return e.button(e.data())})})}).call(this);(function(){var e,t,n,r,i,s,o,u,a,f={}.hasOwnProperty,l=function(e,t){function r(){this.constructor=e}for(var n in t){if(f.call(t,n))e[n]=t[n]}r.prototype=t.prototype;e.prototype=new r;e.__super__=t.prototype;return e};s="modal";i=[];e=function(e){function r(e,t){var n;this.btn=e;this.options=t;this.$btn=$(this.btn);n={target:this.$btn.data("target"),toggle:this.$btn.data("toggle")||"modal",event:"click."+this._name,eventClose:"click."+this._name,backdrop:this.$btn.data("backdrop")||false,push:this.$btn.data("push")||false,beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}};this.options=this._merge(n,this.options);this.$el=$(document).find(this.options.target);this.$btn.on(this.options.event,function(e){return function(t){t.preventDefault();return e.open()}}(this));this._setOptions(this.options);this.$el.find("*[data-dismiss='modal']").on(this.options.event,function(e){return function(){return e.close()}}(this));r.__super__.constructor.call(this,this.$btn,this.options)}l(r,e);r.prototype._name=s;r.prototype._instances=i;r.prototype._setOptions=function(e){var t,n,r;for(t in e){r=e[t];if(this.options[t]==null){return console.error("Maxmertkit Modal. You're trying to set unpropriate option – "+t)}switch(t){case"backdrop":if(r){this.$el.on("click."+this._name,function(e){return function(t){if($(t.target).hasClass("-modal _active_")||$(t.target).hasClass("-carousel")){return e.close()}}}(this))}break;case"push":if(r){n=$(document).find(r);if(n.length){this.$push=$(document).find(r)}}}this.options[t]=r;if(typeof r==="function"){this[t]=this.options[t]}}};r.prototype.destroy=function(){this.$btn.off("."+this._name);return r.__super__.destroy.apply(this,arguments)};r.prototype.open=function(){return n.call(this)};r.prototype.close=function(){return t.call(this)};return r}(MaxmertkitHelpers);u=function(){if(this.$push!=null){this.$push.addClass("-start--");return this.$push.removeClass("-stop--")}};a=function(){if(this.$push!=null){this.$push.addClass("-stop--");this.$push.removeClass("-start--");if(this.$push[0]!=null&&this.$push[0].style!=null&&this.$push[0].style["-webkit-overflow-scrolling"]!=null){return this.$push[0].style["-webkit-overflow-scrolling"]="auto"}}};n=function(){var e;if(this.beforeopen!=null){try{e=this.beforeopen.call(this.$btn);return e.done(function(e){return function(){return o.call(e)}}(this)).fail(function(e){return function(){return e.$el.trigger("fail."+e._name)}}(this))}catch(t){return o.call(this)}}else{return o.call(this)}};o=function(){if(this.$push!=null){$("body").addClass("_perspective_")}this.$el.css({display:"table"});setTimeout(function(e){return function(){e.$el.addClass("_visible_ -start--");e.$el.find(".-dialog").addClass("_visible_ -start--");return u.call(e)}}(this),1);$("body").addClass("_no-scroll_");this.$el.trigger("opened."+this._name);if(this.onopen!=null){try{return this.onopen.call(this.$btn)}catch(e){}}};t=function(){var e;if(this.beforeclose!=null){try{e=this.beforeclose.call(this.$btn);return e.done(function(e){return function(){return r.call(e)}}(this)).fail(function(e){return function(){return e.$el.trigger("fail."+e._name)}}(this))}catch(t){return r.call(this)}}else{return r.call(this)}};r=function(){this.$el.addClass("-stop--");this.$el.find(".-dialog").addClass("-stop--");a.call(this);setTimeout(function(e){return function(){e.$el.removeClass("_visible_ -start-- -stop--");e.$el.find(".-dialog").removeClass("_visible_ -start-- -stop--");$("body").removeClass("_no-scroll_");if(e.$push!=null){$("body").removeClass("_perspective_")}return e.$el.hide()}}(this),1e3);this.$el.trigger("closed."+this._name);if(this.onclose!=null){try{return this.onclose.call(this.$btn)}catch(e){}}};$.fn[s]=function(t){return this.each(function(){if(!$.data(this,"kit-"+s)){$.data(this,"kit-"+s,new e(this,t))}else{if(typeof t==="object"){$.data(this,"kit-"+s)._setOptions(t)}else{if(typeof t==="string"&&t.charAt(0)!=="_"){$.data(this,"kit-"+s)[t]}else{console.error("Maxmertkit error. You passed into the "+s+" something wrong.")}}}})};$(window).on("load",function(){return $('[data-toggle="modal"]').each(function(){var e;e=$(this);return e.modal(e.data())})})}).call(this);(function(){var e,t,n,r,i,s,o,u,a,f={}.hasOwnProperty,l=function(e,t){function r(){this.constructor=e}for(var n in t){if(f.call(t,n))e[n]=t[n]}r.prototype=t.prototype;e.prototype=new r;e.__super__=t.prototype;return e};o="popup";s=[];i=0;e=function(e){function r(e,t){var n;this.btn=e;this.options=t;this.$btn=$(this.btn);this._id=i++;n={target:this.$btn.data("target"),toggle:this.$btn.data("toggle")||"popup",event:"click",eventClose:"click",positionVertical:"top",positionHorizontal:"center",offset:{horizontal:5,vertical:5},closeUnfocus:false,selfish:true};this.options=this._merge(n,this.options);this.beforeopen=this.options.beforeopen;this.onopen=this.options.onopen;this.beforeclose=this.options.beforeclose;this.onclose=this.options.onclose;this.$el=$(document).find(this.options.target);this.$btn.on(this.options.event,function(e){return function(){if(!e.$el.is(":visible")){return e.open()}else{return e.close()}}}(this));this.$btn.on(this.options.eventClose,function(e){return function(){if(e.options.event!==e.options.eventClose){return e.close()}}}(this));this.$el.find("*[data-dismiss='popup']").on(this.options.event,function(e){return function(){return e.close()}}(this));if(this.options.closeUnfocus){$(document).on("click",function(e){return function(t){var n;n="."+e.$el[0].className.split(" ").join(".");if(!$(t.target).closest(n).length&&e.$el.is(":visible")&&!e.$el.is(":animated")&&$(t.target)[0]!==e.$btn[0]){return e.close()}}}(this))}this.$el.removeClass("_top_ _bottom_ _left_ _right_");this.$el.addClass("_"+this.options.positionVertical+"_ _"+this.options.positionHorizontal+"_");r.__super__.constructor.call(this,this.$btn,this.options)}l(r,e);r.prototype._name=o;r.prototype._instances=s;r.prototype._setOptions=function(e){var t,n;for(t in e){n=e[t];if(this.options[t]==null){return console.error("Maxmertkit Popup. You're trying to set unpropriate option.")}switch(t){case"target":this.$el=$(document).find(this.options.target);this.$el.find("*[data-dismiss='popup']").on(this.options.event,function(e){return function(){return e.close()}}(this));break;case"event":this.$btn.off(""+this.options.event+"."+this._name);this.options.event=n;this.$btn.on(""+this.options.event+"."+this._name,function(e){return function(){if(!e.$el.is(":visible")){return e.open()}else{return e.close()}}}(this));break;case"eventClose":this.$btn.off(""+this.options.eventClose+"."+this._name);this.options.eventClose=n;this.$btn.on(""+this.options.eventClose+"."+this._name,function(e){return function(){if(e.options.event!==e.options.eventClose){return e.close()}}}(this));break;case"closeUnfocus":this.options.closeUnfocus=n;$(document).off("click."+this._name);if(this.options.closeUnfocus){$(document).on("click."+this._name,function(e){return function(t){var n;n="."+e.$el[0].className.split(" ").join(".");if(!$(t.target).closest(n).length&&e.$el.is(":visible")&&!e.$el.is(":animated")&&$(t.target)[0]!==e.$btn[0]){return e.close()}}}(this))}break;case"positionVertical":this.$el.removeClass("_top_ _middle_ _bottom_");this.options.positionVertical=n;this.$el.addClass("_"+this.options.positionVertical+"_");break;case"positionHorizontal":this.$el.removeClass("_left_ _center_ _right_");this.options.positionHorizontal=n;this.$el.addClass("_"+this.options.positionHorizontal+"_");break;default:this.options[t]=n}}};r.prototype.destroy=function(){this.$btn.off("."+this._name);return r.__super__.destroy.apply(this,arguments)};r.prototype.open=function(){return n.call(this)};r.prototype.close=function(){return t.call(this)};return r}(MaxmertkitHelpers);a=function(){var e,t,n,r,i,s,o,u;i=this._getScrollParent(this.$el);s=this._getScrollParent(this.$btn);r=this.$btn.offset();n=this.$el.offset();if(i!=null&&i[0]==null||i[0].activeElement.nodeName!=="BODY"){r.top=r.top-$(i).offset().top;r.left=r.left-$(i).offset().left}u={width:this.$btn.outerWidth(),height:this.$btn.outerHeight()};o={width:this.$el.outerWidth(),height:this.$el.outerHeight()};t=e=0;switch(this.options.positionVertical){case"top":t=r.top-o.height-this.options.offset.vertical;break;case"bottom":t=r.top+u.height+this.options.offset.vertical;break;case"middle"||"center":t=r.top+u.height/2-o.height/2}switch(this.options.positionHorizontal){case"center"||"middle":e=r.left+u.width/2-o.width/2;break;case"left":e=r.left-o.width-this.options.offset.horizontal;break;case"right":e=r.left+u.width+this.options.offset.horizontal}return this.$el.css({left:e,top:t})};n=function(){var e;if(this.options.selfish){this._selfish()}if(this.beforeopen!=null){try{e=this.beforeopen.call(this.$btn);return e.done(function(e){return function(){return u.call(e)}}(this)).fail(function(e){return function(){return e.$el.trigger("fail."+e._name)}}(this))}catch(t){return u.call(this)}}else{return u.call(this)}};u=function(){a.call(this);this.$el.addClass("_active_");this.$el.trigger("opened."+this._name);if(this.onopen!=null){try{return this.onopen.call(this.$btn)}catch(e){}}};t=function(){var e;if(this.beforeclose!=null){try{e=this.beforeclose.call(this.$btn);return e.done(function(e){return function(){return r.call(e)}}(this)).fail(function(e){return function(){return e.$el.trigger("fail."+e._name)}}(this))}catch(t){return r.call(this)}}else{return r.call(this)}};r=function(){this.$el.removeClass("_active_");this.$el.trigger("closed."+this._name);if(this.onclose!=null){try{return this.onclose.call(this.$btn)}catch(e){}}};$.fn[o]=function(t){return this.each(function(){if(!$.data(this,"kit-"+o)){$.data(this,"kit-"+o,new e(this,t))}else{if(typeof t==="object"){$.data(this,"kit-"+o)._setOptions(t)}else{if(typeof t==="string"&&t.charAt(0)!=="_"){$.data(this,"kit-"+o)[t]}else{console.error("Maxmertkit Popup. You passed into the "+o+" something wrong.")}}}})}}).call(this);(function(){var e,t,n,r,i,s,o,u,a,f,l,c,h,p={}.hasOwnProperty,d=function(e,t){function r(){this.constructor=e}for(var n in t){if(p.call(t,n))e[n]=t[n]}r.prototype=t.prototype;e.prototype=new r;e.__super__=t.prototype;return e};a="scrollspy";u=[];o=0;e=function(e){function t(e,n){var r;this.el=e;this.options=n;this.$el=$(this.el);this._id=o++;r={spy:this.$el.data("spy")||"scroll",target:this.$el.data("target")||"body",offset:0,elements:"li a",elementsAttr:"href",noMobile:this.$el.data("no-mobile")||true,beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}};this.options=this._merge(r,this.options);this.beforeactive=this.options.beforeactive;this.onactive=this.options.onactive;this.beforeunactive=this.options.beforeunactive;this.onunactive=this.options.onunactive;this.start();t.__super__.constructor.call(this,this.$btn,this.options)}d(t,e);t.prototype._name=a;t.prototype._instances=u;t.prototype._setOptions=function(e){var t,n;for(t in e){n=e[t];if(this.options[t]==null){return console.error("Maxmertkit Scrollspy. You're trying to set unpropriate option.")}this.options[t]=n}};t.prototype.destroy=function(){return t.__super__.destroy.apply(this,arguments)};t.prototype.refresh=function(){return f.call(this)};t.prototype.start=function(){return r.call(this)};t.prototype.stop=function(){return i.call(this)};return t}(MaxmertkitHelpers);n=function(e){var t,n,r,i;i=this.elements;for(n=0,r=i.length;n<r;n++){t=i[n];t.menu.removeClass("_active_")}return this.elements[e].menu.addClass("_active_").parents("li").addClass("_active_")};s=function(e){return this.elements[e].menu.removeClass("_active_")};f=function(){this.elements=[];return this.$el.find(this.options.elements).each(function(e){return function(t,n){var r,i;i=$(n).attr(e.options.elementsAttr);if(i!=null){r=$(e.options.target).find(i);if(r.length){return e.elements.push({menu:$(n).parent(),item:r.parent(),itemHeight:r.parent().height(),offsetTop:r.position().top})}}}}(this))};l=function(e){var t,r,i;t=0;i=[];while(t<this.elements.length){if(this.elements[t].offsetTop<=(r=(e.currentTarget.scrollTop||e.currentTarget.scrollY)+this.options.offset)&&r<=this.elements[t].offsetTop+this.elements[t].itemHeight){if(!this.elements[t].menu.hasClass("_active_")){n.call(this,t)}}else{if(this.elements[t].menu.hasClass("_active_")&&(e.currentTarget.scrollTop||e.currentTarget.scrollY)+this.options.offset<this.elements[t].offsetTop+this.elements[t].itemHeight){s.call(this,t)}}i.push(t++)}return i};t=function(){var e;if(this.options.target==="body"){e=window}else{e=this.options.target}return $(e).on("scroll."+this._name+"."+this._id,function(e){return function(t){return l.call(e,t)}}(this))};r=function(){var e;this.refresh();if(this.beforeactive!=null){try{e=this.beforeactive.call(this.$el);return e.done(function(e){return function(){return c.call(e)}}(this)).fail(function(e){return function(){return e.$el.trigger("fail."+e._name)}}(this))}catch(t){return c.call(this)}}else{return c.call(this)}};c=function(){t.call(this);this.$el.addClass("_active_");this.$el.trigger("started."+this._name);if(this.onactive!=null){try{return this.onactive.call(this.$el)}catch(e){}}};i=function(){var e;if(this.beforeunactive!=null){try{e=this.beforeunactive.call(this.$el);return e.done(function(e){return function(){return h.call(e)}}(this)).fail(function(e){return function(){return e.$el.trigger("fail."+e._name)}}(this))}catch(t){return h.call(this)}}else{return h.call(this)}};h=function(){var e;if(this.options.target==="body"){e=window}else{e=this.options.target}$(e).off("scroll."+this._name+"."+this._id);this.$el.trigger("stopped."+this._name);if(this.onunactive!=null){try{return this.onunactive.call(this.$el)}catch(t){}}};$.fn[a]=function(t){return this.each(function(){if(!$.data(this,"kit-"+a)){$.data(this,"kit-"+a,new e(this,t))}else{if(typeof t==="object"){$.data(this,"kit-"+a)._setOptions(t)}else{if(typeof t==="string"&&t.charAt(0)!=="_"){$.data(this,"kit-"+a)[t]}else{console.error("Maxmertkit Affix. You passed into the "+a+" something wrong.")}}}})}}).call(this);(function(){var e,t,n,r,i,s,o,u,a={}.hasOwnProperty,f=function(e,t){function r(){this.constructor=e}for(var n in t){if(a.call(t,n))e[n]=t[n]}r.prototype=t.prototype;e.prototype=new r;e.__super__=t.prototype;return e};u="tabs";o=[];s=0;e=function(e){function t(e,n){var r;this.tab=e;this.options=n;this.$tab=$(this.tab);this._id=s++;r={toggle:this.$tab.data("toggle")||"tabs",group:this.$tab.data("group")||null,target:this.$tab.data("target")||null,event:"click",active:0,beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}};this.options=this._merge(r,this.options);this.beforeactive=this.options.beforeactive;this.onactive=this.options.onactive;this.beforeunactive=this.options.beforeunactive;this.onunactive=this.options.onunactive;this.$tab.on(this.options.event,function(e){return function(){if(!e.$tab.hasClass("_active_")){return e.activate()}}}(this));this.$content=$(document).find(this.options.target);this.$content.hide();t.__super__.constructor.call(this,this.$tab,this.options)}f(t,e);t.prototype._name=u;t.prototype._instances=o;t.prototype._setOptions=function(e){var t,n;for(t in e){n=e[t];if(this.options[t]==null){return console.error("Maxmertkit Tabs. You're trying to set unpropriate option.")}switch(t){case"event":this.$tab.off(""+this.options.event+"."+this._name);this.options.event=n;this.$tab.on(""+this.options.event+"."+this._name,function(e){return function(){if(e.$tab.hasClass("_active_")){return e.deactivate()}else{return e.activate()}}}(this));break;case"target":this.options.target=n;this.$content=$(document).find(this.options.target);break;default:this.options[t]=n;if(typeof n==="function"){this[t]=this.options[t]}}}};t.prototype._afterConstruct=function(){var e;e=0;while(e<this._instances&&this._instances[e].group!==this.options.group){e++}return this._instances[e].activate()};t.prototype.destroy=function(){this.$tab.off("."+this._name);return t.__super__.destroy.apply(this,arguments)};t.prototype.activate=function(){return n.call(this)};t.prototype.deactivate=function(){if(this.$tab.hasClass("_active_")){return r.call(this)}};t.prototype.disable=function(){return this.$tab.toggleClass("_disabled_")};return t}(MaxmertkitHelpers);n=function(){var e;if(this.options.selfish){this._selfish()}if(this.beforeactive!=null){try{e=this.beforeactive.call(this.$tab);return e.done(function(e){return function(){return t.call(e)}}(this)).fail(function(e){return function(){return e.$tab.trigger("fail."+e._name)}}(this))}catch(n){return t.call(this)}}else{return t.call(this)}};t=function(){var e,t,n,r;r=this._instances;for(t=0,n=r.length;t<n;t++){e=r[t];if(this._id!==e._id&&e.options.group===this.options.group){e.deactivate()}}this.$tab.addClass("_active_");this.$tab.trigger("activated."+this._name);this.$content.show();if(this.onactive!=null){try{return this.onactive.call(this.$tab)}catch(i){}}};r=function(){var e;if(this.beforeunactive!=null){try{e=this.beforeunactive.call(this.$tab);return e.done(function(e){return function(){return i.call(e)}}(this)).fail(function(e){return function(){return e.$tab.trigger("fail."+e._name)}}(this))}catch(t){return i.call(this)}}else{return i.call(this)}};i=function(){this.$tab.removeClass("_active_");this.$tab.trigger("deactivated."+this._name);this.$content.hide();if(this.onunactive!=null){try{return this.onunactive.call(this.$tab)}catch(e){}}};$.fn[u]=function(t){return this.each(function(){if(!$.data(this,"kit-"+u)){$.data(this,"kit-"+u,new e(this,t))}else{if(typeof t==="object"){$.data(this,"kit-"+u)._setOptions(t)}else{if(typeof t==="string"&&t.charAt(0)!=="_"){$.data(this,"kit-"+u)[t]}else{console.error("Maxmertkit Tabs. You passed into the "+u+" something wrong.")}}}})}}).call(this)
packager/react-packager/src/SocketInterface/__tests__/SocketInterface-test.js
JulienThibeaut/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. */ 'use strict'; jest.setMock('worker-farm', function() { return () => {}; }) .setMock('uglify-js') .mock('child_process') .dontMock('../'); describe('SocketInterface', () => { let SocketInterface; let SocketClient; beforeEach(() => { SocketInterface = require('../'); SocketClient = require('../SocketClient'); }); describe('getOrCreateSocketFor', () => { pit('creates socket path by hashing options', () => { const fs = require('fs'); fs.existsSync = jest.genMockFn().mockImpl(() => true); fs.unlinkSync = jest.genMockFn(); let callback; require('child_process').spawn.mockImpl(() => ({ on: (event, cb) => callback = cb, send: (message) => { setImmediate(() => callback({ type: 'createdServer' })); }, unref: () => undefined, disconnect: () => undefined, })); // Check that given two equivelant server options, we end up with the same // socket path. const options1 = { projectRoots: ['/root'], transformModulePath: '/root/foo' }; const options2 = { transformModulePath: '/root/foo', projectRoots: ['/root'] }; const options3 = { projectRoots: ['/root', '/root2'] }; return SocketInterface.getOrCreateSocketFor(options1).then(() => { expect(SocketClient.create).toBeCalled(); return SocketInterface.getOrCreateSocketFor(options2).then(() => { expect(SocketClient.create.mock.calls.length).toBe(2); expect(SocketClient.create.mock.calls[0]).toEqual(SocketClient.create.mock.calls[1]); return SocketInterface.getOrCreateSocketFor(options3).then(() => { expect(SocketClient.create.mock.calls.length).toBe(3); expect(SocketClient.create.mock.calls[1]).not.toEqual(SocketClient.create.mock.calls[2]); }); }); }); }); pit('should fork a server', () => { const fs = require('fs'); fs.existsSync = jest.genMockFn().mockImpl(() => false); fs.unlinkSync = jest.genMockFn(); let sockPath; let callback; require('child_process').spawn.mockImpl(() => ({ on: (event, cb) => callback = cb, send: (message) => { expect(message.type).toBe('createSocketServer'); expect(message.data.options).toEqual({ projectRoots: ['/root'] }); expect(message.data.sockPath).toContain('react-packager'); sockPath = message.data.sockPath; setImmediate(() => callback({ type: 'createdServer' })); }, unref: () => undefined, disconnect: () => undefined, })); return SocketInterface.getOrCreateSocketFor({ projectRoots: ['/root'] }) .then(() => { expect(SocketClient.create).toBeCalledWith(sockPath); }); }); }); });
src/svg-icons/hardware/phone-iphone.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwarePhoneIphone = (props) => ( <SvgIcon {...props}> <path d="M15.5 1h-8C6.12 1 5 2.12 5 3.5v17C5 21.88 6.12 23 7.5 23h8c1.38 0 2.5-1.12 2.5-2.5v-17C18 2.12 16.88 1 15.5 1zm-4 21c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5-4H7V4h9v14z"/> </SvgIcon> ); HardwarePhoneIphone = pure(HardwarePhoneIphone); HardwarePhoneIphone.displayName = 'HardwarePhoneIphone'; HardwarePhoneIphone.muiName = 'SvgIcon'; export default HardwarePhoneIphone;
app/jsx/external_apps/components/ExternalToolsTable.js
venturehive/canvas-lms
/* * Copyright (C) 2014 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import _ from 'underscore' import I18n from 'i18n!external_tools' import React from 'react' import PropTypes from 'prop-types' import store from 'jsx/external_apps/lib/ExternalAppsStore' import ExternalToolsTableRow from 'jsx/external_apps/components/ExternalToolsTableRow' import InfiniteScroll from 'jsx/external_apps/components/InfiniteScroll' import ScreenReaderContent from 'instructure-ui/lib/components/ScreenReaderContent' export default React.createClass({ displayName: 'ExternalToolsTable', propTypes: { canAddEdit: PropTypes.bool.isRequired }, getInitialState() { return store.getState(); }, onChange() { this.setState(store.getState()); }, componentDidMount() { store.addChangeListener(this.onChange); store.fetch(); }, componentWillUnmount() { store.removeChangeListener(this.onChange); }, loadMore(page) { if (store.getState().hasMore && !store.getState().isLoading) { store.fetch(); } }, loader() { return <div className="loadingIndicator"></div>; }, trs() { if (store.getState().externalTools.length == 0) { return null; } return store.getState().externalTools.map(function (tool, idx) { return <ExternalToolsTableRow key={idx} tool={tool} canAddEdit={this.props.canAddEdit}/> }.bind(this)); }, render() { return ( <div className="ExternalToolsTable"> <InfiniteScroll pageStart={0} loadMore={this.loadMore} hasMore={store.getState().hasMore} loader={this.loader()}> <table className="ic-Table ic-Table--striped ic-Table--condensed" id="external-tools-table"> <caption className="screenreader-only">{I18n.t('External Apps')}</caption> <thead> <tr> <th scope="col" width="5%"><ScreenReaderContent>{I18n.t('Status')}</ScreenReaderContent></th> <th scope="col" width="65%">{I18n.t('Name')}</th> <th scope="col" width="30%"><ScreenReaderContent>{I18n.t('Actions')}</ScreenReaderContent></th> </tr> </thead> <tbody className="collectionViewItems"> {this.trs()} </tbody> </table> </InfiniteScroll> </div> ); } });
src/RootComponent.js
alelk/houses-building-website
/** * Root Component * * Created by Alex Elkin on 04.11.2017. */ import App from './app/App'; import React from 'react'; import {Responsive} from 'semantic-ui-react' const RootComponent = (props) => ( <div className="RootComponent"> <Responsive as={App} {...Responsive.onlyMobile} {...props} mobile/> <Responsive as={App} {...Responsive.onlyTablet} {...props}/> <Responsive as={App} {...Responsive.onlyComputer} {...props}/> </div> ); export default RootComponent;
testClient/components/CurrStats.js
DataHiveDJW/ServerHive
import React from 'react'; import Bar from './Bar'; const normalizeBars = (keys, currStats) => { let divisor = 1; for (let i = 0; i < keys.length; i += 1) { // console.log('yo', currStats[keys[i]]); if (currStats[keys[i]] > 75 && currStats[keys[i]] / 75 > divisor) divisor = Math.floor(currStats[keys[i]] / 75) + 1; } // console.log(divisor); return divisor } const CurrStats = (props) => { // console.log(props.currStats); const keys = props.currStats === undefined ? [] : Object.keys(props.currStats); const session = []; const rp = []; let rpVolume = 0; let targetVolume = 0; for (let i = 0; i < keys.length; i += 1) { // console.log(keys[i]); if (keys[i] !== 'session' && keys[i] !== 'Cached Response') { targetVolume += props.currStats[keys[i]] session.push( <Bar server={keys[i]} requests={props.currStats[keys[i]]} divisor={normalizeBars(keys, props.currStats)} /> ); } if (keys[i] === 'Cached Response') { rpVolume += props.currStats[keys[i]] rp.push( <Bar server={keys[i]} requests={props.currStats[keys[i]]} divisor={normalizeBars(keys, props.currStats)} /> ); } } return ( <div id = 'panel'> <h1>nodeXchange</h1> <div id='rp'> <h2>Cache Response Volume: {rpVolume}</h2> {rp} </div> <div id='appServers'> <h2>App Server Response Volume: {targetVolume}</h2> {session} </div> </div> ) } export default CurrStats;
src/svg-icons/hardware/sim-card.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareSimCard = (props) => ( <SvgIcon {...props}> <path d="M19.99 4c0-1.1-.89-2-1.99-2h-8L4 8v12c0 1.1.9 2 2 2h12.01c1.1 0 1.99-.9 1.99-2l-.01-16zM9 19H7v-2h2v2zm8 0h-2v-2h2v2zm-8-4H7v-4h2v4zm4 4h-2v-4h2v4zm0-6h-2v-2h2v2zm4 2h-2v-4h2v4z"/> </SvgIcon> ); HardwareSimCard = pure(HardwareSimCard); HardwareSimCard.displayName = 'HardwareSimCard'; HardwareSimCard.muiName = 'SvgIcon'; export default HardwareSimCard;
api/swagger/doc/swagger-ui-standalone-preset.js
flasomm/backoffice-react-swagger-api
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SwaggerUIStandalonePreset=t():e.SwaggerUIStandalonePreset=t()}(this,function(){return function(e){function t(r){if(o[r])return o[r].exports;var n=o[r]={exports:{},id:r,loaded:!1};return e[r].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var o={};return t.m=e,t.c=o,t.p="/dist",t(0)}([function(e,t,o){e.exports=o(1)},function(e,t,o){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var n=o(2),i=r(n);o(30);var a=o(34),s=r(a),l=[s.default,function(){return{components:{StandaloneLayout:i.default}}}];e.exports=l},function(e,t,o){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var o=0;o<t.length;o++){var r=t[o];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,o,r){return o&&e(t.prototype,o),r&&e(t,r),t}}(),l=o(3),p=r(l),u=function(e){function t(){return n(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.specSelectors,o=e.specActions,r=e.getComponent,n=t.info(),i=t.url(),a=t.basePath(),s=t.host(),l=t.securityDefinitions(),u=t.externalDocs(),c=t.schemes(),f=r("info"),d=r("operations",!0),g=r("models",!0),b=r("authorizeBtn",!0),m=r("Container"),x=r("Row"),w=r("Col"),h=r("errors",!0),y=r("schemes"),k=r("Topbar",!0),v=r("onlineValidatorBadge",!0),E=t.loadingStatus();return p.default.createElement(m,{className:"swagger-ui"},k?p.default.createElement(k,null):null,"loading"===E&&p.default.createElement("div",{className:"info"},p.default.createElement("h4",{className:"title"},"Loading...")),"failed"===E&&p.default.createElement("div",{className:"info"},p.default.createElement("h4",{className:"title"},"Failed to load spec.")),"failedConfig"===E&&p.default.createElement("div",{className:"info",style:{maxWidth:"880px",marginLeft:"auto",marginRight:"auto",textAlign:"center"}},p.default.createElement("h4",{className:"title"},"Failed to load config.")),"success"===E&&p.default.createElement("div",null,p.default.createElement(h,null),p.default.createElement(x,{className:"information-container"},p.default.createElement(w,{mobile:12},n.count()?p.default.createElement(f,{info:n,url:i,host:s,basePath:a,externalDocs:u,getComponent:r}):null)),c&&c.size||l?p.default.createElement("div",{className:"scheme-container"},p.default.createElement(w,{className:"schemes wrapper",mobile:12},c&&c.size?p.default.createElement(y,{schemes:c,specActions:o}):null,l?p.default.createElement(b,null):null)):null,p.default.createElement(x,null,p.default.createElement(w,{mobile:12,desktop:12},p.default.createElement(d,null))),p.default.createElement(x,null,p.default.createElement(w,{mobile:12,desktop:12},p.default.createElement(g,null)))),p.default.createElement(x,null,p.default.createElement(w,null,p.default.createElement(v,null))))}}]),t}(p.default.Component);u.propTypes={errSelectors:l.PropTypes.object.isRequired,errActions:l.PropTypes.object.isRequired,specActions:l.PropTypes.object.isRequired,specSelectors:l.PropTypes.object.isRequired,layoutSelectors:l.PropTypes.object.isRequired,layoutActions:l.PropTypes.object.isRequired,getComponent:l.PropTypes.func.isRequired},t.default=u},function(e,t,o){"use strict";e.exports=o(4)},function(e,t,o){"use strict";var r=o(5),n=o(6),i=o(19),a=o(22),s=o(23),l=o(25),p=o(10),u=o(26),c=o(28),f=o(29),d=(o(12),p.createElement),g=p.createFactory,b=p.cloneElement,m=r,x={Children:{map:n.map,forEach:n.forEach,count:n.count,toArray:n.toArray,only:f},Component:i,PureComponent:a,createElement:d,cloneElement:b,isValidElement:p.isValidElement,PropTypes:u,createClass:s.createClass,createFactory:g,createMixin:function(e){return e},DOM:l,version:c,__spread:m};e.exports=x},function(e,t){/* object-assign (c) Sindre Sorhus @license MIT */ "use strict";function o(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},o=0;o<10;o++)t["_"+String.fromCharCode(o)]=o;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}var n=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,s,l=o(e),p=1;p<arguments.length;p++){r=Object(arguments[p]);for(var u in r)i.call(r,u)&&(l[u]=r[u]);if(n){s=n(r);for(var c=0;c<s.length;c++)a.call(r,s[c])&&(l[s[c]]=r[s[c]])}}return l}},function(e,t,o){"use strict";function r(e){return(""+e).replace(y,"$&/")}function n(e,t){this.func=e,this.context=t,this.count=0}function i(e,t,o){var r=e.func,n=e.context;r.call(n,t,e.count++)}function a(e,t,o){if(null==e)return e;var r=n.getPooled(t,o);x(e,i,r),n.release(r)}function s(e,t,o,r){this.result=e,this.keyPrefix=t,this.func=o,this.context=r,this.count=0}function l(e,t,o){var n=e.result,i=e.keyPrefix,a=e.func,s=e.context,l=a.call(s,t,e.count++);Array.isArray(l)?p(l,n,o,m.thatReturnsArgument):null!=l&&(b.isValidElement(l)&&(l=b.cloneAndReplaceKey(l,i+(!l.key||t&&t.key===l.key?"":r(l.key)+"/")+o)),n.push(l))}function p(e,t,o,n,i){var a="";null!=o&&(a=r(o)+"/");var p=s.getPooled(t,a,n,i);x(e,l,p),s.release(p)}function u(e,t,o){if(null==e)return e;var r=[];return p(e,r,null,t,o),r}function c(e,t,o){return null}function f(e,t){return x(e,c,null)}function d(e){var t=[];return p(e,t,null,m.thatReturnsArgument),t}var g=o(7),b=o(10),m=o(13),x=o(16),w=g.twoArgumentPooler,h=g.fourArgumentPooler,y=/\/+/g;n.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},g.addPoolingTo(n,w),s.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},g.addPoolingTo(s,h);var k={forEach:a,map:u,mapIntoWithKeyPrefixInternal:p,count:f,toArray:d};e.exports=k},function(e,t,o){"use strict";var r=o(8),n=(o(9),function(e){var t=this;if(t.instancePool.length){var o=t.instancePool.pop();return t.call(o,e),o}return new t(e)}),i=function(e,t){var o=this;if(o.instancePool.length){var r=o.instancePool.pop();return o.call(r,e,t),r}return new o(e,t)},a=function(e,t,o){var r=this;if(r.instancePool.length){var n=r.instancePool.pop();return r.call(n,e,t,o),n}return new r(e,t,o)},s=function(e,t,o,r){var n=this;if(n.instancePool.length){var i=n.instancePool.pop();return n.call(i,e,t,o,r),i}return new n(e,t,o,r)},l=function(e){var t=this;e instanceof t?void 0:r("25"),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},p=10,u=n,c=function(e,t){var o=e;return o.instancePool=[],o.getPooled=t||u,o.poolSize||(o.poolSize=p),o.release=l,o},f={addPoolingTo:c,oneArgumentPooler:n,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:s};e.exports=f},function(e,t){"use strict";function o(e){for(var t=arguments.length-1,o="Minified React error #"+e+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)o+="&args[]="+encodeURIComponent(arguments[r+1]);o+=" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";var n=new Error(o);throw n.name="Invariant Violation",n.framesToPop=1,n}e.exports=o},function(e,t,o){"use strict";function r(e,t,o,r,i,a,s,l){if(n(t),!e){var p;if(void 0===t)p=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[o,r,i,a,s,l],c=0;p=new Error(t.replace(/%s/g,function(){return u[c++]})),p.name="Invariant Violation"}throw p.framesToPop=1,p}}var n=function(e){};e.exports=r},function(e,t,o){"use strict";function r(e){return void 0!==e.ref}function n(e){return void 0!==e.key}var i=o(5),a=o(11),s=(o(12),o(14),Object.prototype.hasOwnProperty),l=o(15),p={key:!0,ref:!0,__self:!0,__source:!0},u=function(e,t,o,r,n,i,a){var s={$$typeof:l,type:e,key:t,ref:o,props:a,_owner:i};return s};u.createElement=function(e,t,o){var i,l={},c=null,f=null,d=null,g=null;if(null!=t){r(t)&&(f=t.ref),n(t)&&(c=""+t.key),d=void 0===t.__self?null:t.__self,g=void 0===t.__source?null:t.__source;for(i in t)s.call(t,i)&&!p.hasOwnProperty(i)&&(l[i]=t[i])}var b=arguments.length-2;if(1===b)l.children=o;else if(b>1){for(var m=Array(b),x=0;x<b;x++)m[x]=arguments[x+2];l.children=m}if(e&&e.defaultProps){var w=e.defaultProps;for(i in w)void 0===l[i]&&(l[i]=w[i])}return u(e,c,f,d,g,a.current,l)},u.createFactory=function(e){var t=u.createElement.bind(null,e);return t.type=e,t},u.cloneAndReplaceKey=function(e,t){var o=u(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return o},u.cloneElement=function(e,t,o){var l,c=i({},e.props),f=e.key,d=e.ref,g=e._self,b=e._source,m=e._owner;if(null!=t){r(t)&&(d=t.ref,m=a.current),n(t)&&(f=""+t.key);var x;e.type&&e.type.defaultProps&&(x=e.type.defaultProps);for(l in t)s.call(t,l)&&!p.hasOwnProperty(l)&&(void 0===t[l]&&void 0!==x?c[l]=x[l]:c[l]=t[l])}var w=arguments.length-2;if(1===w)c.children=o;else if(w>1){for(var h=Array(w),y=0;y<w;y++)h[y]=arguments[y+2];c.children=h}return u(e.type,f,d,g,b,m,c)},u.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===l},e.exports=u},function(e,t){"use strict";var o={current:null};e.exports=o},function(e,t,o){"use strict";var r=o(13),n=r;e.exports=n},function(e,t){"use strict";function o(e){return function(){return e}}var r=function(){};r.thatReturns=o,r.thatReturnsFalse=o(!1),r.thatReturnsTrue=o(!0),r.thatReturnsNull=o(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},e.exports=r},function(e,t,o){"use strict";var r=!1;e.exports=r},function(e,t){"use strict";var o="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;e.exports=o},function(e,t,o){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?p.escape(e.key):t.toString(36)}function n(e,t,o,i){var f=typeof e;if("undefined"!==f&&"boolean"!==f||(e=null),null===e||"string"===f||"number"===f||"object"===f&&e.$$typeof===s)return o(i,e,""===t?u+r(e,0):t),1;var d,g,b=0,m=""===t?u:t+c;if(Array.isArray(e))for(var x=0;x<e.length;x++)d=e[x],g=m+r(d,x),b+=n(d,g,o,i);else{var w=l(e);if(w){var h,y=w.call(e);if(w!==e.entries)for(var k=0;!(h=y.next()).done;)d=h.value,g=m+r(d,k++),b+=n(d,g,o,i);else for(;!(h=y.next()).done;){var v=h.value;v&&(d=v[1],g=m+p.escape(v[0])+c+r(d,0),b+=n(d,g,o,i))}}else if("object"===f){var E="",A=String(e);a("31","[object Object]"===A?"object with keys {"+Object.keys(e).join(", ")+"}":A,E)}}return b}function i(e,t,o){return null==e?0:n(e,"",t,o)}var a=o(8),s=(o(11),o(15)),l=o(17),p=(o(9),o(18)),u=(o(12),"."),c=":";e.exports=i},function(e,t){"use strict";function o(e){var t=e&&(r&&e[r]||e[n]);if("function"==typeof t)return t}var r="function"==typeof Symbol&&Symbol.iterator,n="@@iterator";e.exports=o},function(e,t){"use strict";function o(e){var t=/[=:]/g,o={"=":"=0",":":"=2"},r=(""+e).replace(t,function(e){return o[e]});return"$"+r}function r(e){var t=/(=0|=2)/g,o={"=0":"=","=2":":"},r="."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1);return(""+r).replace(t,function(e){return o[e]})}var n={escape:o,unescape:r};e.exports=n},function(e,t,o){"use strict";function r(e,t,o){this.props=e,this.context=t,this.refs=a,this.updater=o||i}var n=o(8),i=o(20),a=(o(14),o(21));o(9),o(12);r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e?n("85"):void 0,this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t,"setState")},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e,"forceUpdate")};e.exports=r},function(e,t,o){"use strict";function r(e,t){}var n=(o(12),{isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e,t){r(e,"replaceState")},enqueueSetState:function(e,t){r(e,"setState")}});e.exports=n},function(e,t,o){"use strict";var r={};e.exports=r},function(e,t,o){"use strict";function r(e,t,o){this.props=e,this.context=t,this.refs=l,this.updater=o||s}function n(){}var i=o(5),a=o(19),s=o(20),l=o(21);n.prototype=a.prototype,r.prototype=new n,r.prototype.constructor=r,i(r.prototype,a.prototype),r.prototype.isPureReactComponent=!0,e.exports=r},function(e,t,o){"use strict";function r(e){return e}function n(e,t){var o=y.hasOwnProperty(t)?y[t]:null;v.hasOwnProperty(t)&&("OVERRIDE_BASE"!==o?f("73",t):void 0),e&&("DEFINE_MANY"!==o&&"DEFINE_MANY_MERGED"!==o?f("74",t):void 0)}function i(e,t){if(t){"function"==typeof t?f("75"):void 0,b.isValidElement(t)?f("76"):void 0;var o=e.prototype,r=o.__reactAutoBindPairs;t.hasOwnProperty(w)&&k.mixins(e,t.mixins);for(var i in t)if(t.hasOwnProperty(i)&&i!==w){var a=t[i],s=o.hasOwnProperty(i);if(n(s,i),k.hasOwnProperty(i))k[i](e,a);else{var u=y.hasOwnProperty(i),c="function"==typeof a,d=c&&!u&&!s&&t.autobind!==!1;if(d)r.push(i,a),o[i]=a;else if(s){var g=y[i];!u||"DEFINE_MANY_MERGED"!==g&&"DEFINE_MANY"!==g?f("77",g,i):void 0,"DEFINE_MANY_MERGED"===g?o[i]=l(o[i],a):"DEFINE_MANY"===g&&(o[i]=p(o[i],a))}else o[i]=a}}}else;}function a(e,t){if(t)for(var o in t){var r=t[o];if(t.hasOwnProperty(o)){var n=o in k;n?f("78",o):void 0;var i=o in e;i?f("79",o):void 0,e[o]=r}}}function s(e,t){e&&t&&"object"==typeof e&&"object"==typeof t?void 0:f("80");for(var o in t)t.hasOwnProperty(o)&&(void 0!==e[o]?f("81",o):void 0,e[o]=t[o]);return e}function l(e,t){return function(){var o=e.apply(this,arguments),r=t.apply(this,arguments);if(null==o)return r;if(null==r)return o;var n={};return s(n,o),s(n,r),n}}function p(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function u(e,t){var o=t.bind(e);return o}function c(e){for(var t=e.__reactAutoBindPairs,o=0;o<t.length;o+=2){var r=t[o],n=t[o+1];e[r]=u(e,n)}}var f=o(8),d=o(5),g=o(19),b=o(10),m=(o(24),o(20)),x=o(21),w=(o(9),o(12),"mixins"),h=[],y={mixins:"DEFINE_MANY",statics:"DEFINE_MANY",propTypes:"DEFINE_MANY",contextTypes:"DEFINE_MANY",childContextTypes:"DEFINE_MANY",getDefaultProps:"DEFINE_MANY_MERGED",getInitialState:"DEFINE_MANY_MERGED",getChildContext:"DEFINE_MANY_MERGED",render:"DEFINE_ONCE",componentWillMount:"DEFINE_MANY",componentDidMount:"DEFINE_MANY",componentWillReceiveProps:"DEFINE_MANY",shouldComponentUpdate:"DEFINE_ONCE",componentWillUpdate:"DEFINE_MANY",componentDidUpdate:"DEFINE_MANY",componentWillUnmount:"DEFINE_MANY",updateComponent:"OVERRIDE_BASE"},k={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var o=0;o<t.length;o++)i(e,t[o])},childContextTypes:function(e,t){e.childContextTypes=d({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=d({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=l(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=d({},e.propTypes,t)},statics:function(e,t){a(e,t)},autobind:function(){}},v={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t,"replaceState")},isMounted:function(){return this.updater.isMounted(this)}},E=function(){};d(E.prototype,g.prototype,v);var A={createClass:function(e){var t=r(function(e,o,r){this.__reactAutoBindPairs.length&&c(this),this.props=e,this.context=o,this.refs=x,this.updater=r||m,this.state=null;var n=this.getInitialState?this.getInitialState():null;"object"!=typeof n||Array.isArray(n)?f("82",t.displayName||"ReactCompositeComponent"):void 0,this.state=n});t.prototype=new E,t.prototype.constructor=t,t.prototype.__reactAutoBindPairs=[],h.forEach(i.bind(null,t)),i(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render?void 0:f("83");for(var o in y)t.prototype[o]||(t.prototype[o]=null);return t},injection:{injectMixin:function(e){h.push(e)}}};e.exports=A},function(e,t,o){"use strict";var r={};e.exports=r},function(e,t,o){"use strict";var r=o(10),n=r.createFactory,i={a:n("a"),abbr:n("abbr"),address:n("address"),area:n("area"),article:n("article"),aside:n("aside"),audio:n("audio"),b:n("b"),base:n("base"),bdi:n("bdi"),bdo:n("bdo"),big:n("big"),blockquote:n("blockquote"),body:n("body"),br:n("br"),button:n("button"),canvas:n("canvas"),caption:n("caption"),cite:n("cite"),code:n("code"),col:n("col"),colgroup:n("colgroup"),data:n("data"),datalist:n("datalist"),dd:n("dd"),del:n("del"),details:n("details"),dfn:n("dfn"),dialog:n("dialog"),div:n("div"),dl:n("dl"),dt:n("dt"),em:n("em"),embed:n("embed"),fieldset:n("fieldset"),figcaption:n("figcaption"),figure:n("figure"),footer:n("footer"),form:n("form"),h1:n("h1"),h2:n("h2"),h3:n("h3"),h4:n("h4"),h5:n("h5"),h6:n("h6"),head:n("head"),header:n("header"),hgroup:n("hgroup"),hr:n("hr"),html:n("html"),i:n("i"),iframe:n("iframe"),img:n("img"),input:n("input"),ins:n("ins"),kbd:n("kbd"),keygen:n("keygen"),label:n("label"),legend:n("legend"),li:n("li"),link:n("link"),main:n("main"),map:n("map"),mark:n("mark"),menu:n("menu"),menuitem:n("menuitem"),meta:n("meta"),meter:n("meter"),nav:n("nav"),noscript:n("noscript"),object:n("object"),ol:n("ol"),optgroup:n("optgroup"),option:n("option"),output:n("output"),p:n("p"),param:n("param"),picture:n("picture"),pre:n("pre"),progress:n("progress"),q:n("q"),rp:n("rp"),rt:n("rt"),ruby:n("ruby"),s:n("s"),samp:n("samp"),script:n("script"),section:n("section"),select:n("select"),small:n("small"),source:n("source"),span:n("span"),strong:n("strong"),style:n("style"),sub:n("sub"),summary:n("summary"),sup:n("sup"),table:n("table"),tbody:n("tbody"),td:n("td"),textarea:n("textarea"),tfoot:n("tfoot"),th:n("th"),thead:n("thead"),time:n("time"),title:n("title"),tr:n("tr"),track:n("track"),u:n("u"),ul:n("ul"),var:n("var"),video:n("video"),wbr:n("wbr"),circle:n("circle"),clipPath:n("clipPath"),defs:n("defs"),ellipse:n("ellipse"),g:n("g"),image:n("image"),line:n("line"),linearGradient:n("linearGradient"),mask:n("mask"),path:n("path"),pattern:n("pattern"),polygon:n("polygon"),polyline:n("polyline"),radialGradient:n("radialGradient"),rect:n("rect"),stop:n("stop"),svg:n("svg"),text:n("text"),tspan:n("tspan")};e.exports=i},function(e,t,o){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function n(e){this.message=e,this.stack=""}function i(e){function t(t,o,r,i,a,s,l){i=i||P,s=s||r;if(null==o[r]){var p=v[a];return t?new n(null===o[r]?"The "+p+" `"+s+"` is marked as required "+("in `"+i+"`, but its value is `null`."):"The "+p+" `"+s+"` is marked as required in "+("`"+i+"`, but its value is `undefined`.")):null}return e(o,r,i,a,s)}var o=t.bind(null,!1);return o.isRequired=t.bind(null,!0),o}function a(e){function t(t,o,r,i,a,s){var l=t[o],p=w(l);if(p!==e){var u=v[i],c=h(l);return new n("Invalid "+u+" `"+a+"` of type "+("`"+c+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return i(t)}function s(){return i(A.thatReturns(null))}function l(e){function t(t,o,r,i,a){if("function"!=typeof e)return new n("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var s=t[o];if(!Array.isArray(s)){var l=v[i],p=w(s);return new n("Invalid "+l+" `"+a+"` of type "+("`"+p+"` supplied to `"+r+"`, expected an array."))}for(var u=0;u<s.length;u++){var c=e(s,u,r,i,a+"["+u+"]",E);if(c instanceof Error)return c}return null}return i(t)}function p(){function e(e,t,o,r,i){var a=e[t];if(!k.isValidElement(a)){var s=v[r],l=w(a);return new n("Invalid "+s+" `"+i+"` of type "+("`"+l+"` supplied to `"+o+"`, expected a single ReactElement."))}return null}return i(e)}function u(e){function t(t,o,r,i,a){if(!(t[o]instanceof e)){var s=v[i],l=e.name||P,p=y(t[o]);return new n("Invalid "+s+" `"+a+"` of type "+("`"+p+"` supplied to `"+r+"`, expected ")+("instance of `"+l+"`."))}return null}return i(t)}function c(e){function t(t,o,i,a,s){for(var l=t[o],p=0;p<e.length;p++)if(r(l,e[p]))return null;var u=v[a],c=JSON.stringify(e);return new n("Invalid "+u+" `"+s+"` of value `"+l+"` "+("supplied to `"+i+"`, expected one of "+c+"."))}return Array.isArray(e)?i(t):A.thatReturnsNull}function f(e){function t(t,o,r,i,a){if("function"!=typeof e)return new n("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var s=t[o],l=w(s);if("object"!==l){var p=v[i];return new n("Invalid "+p+" `"+a+"` of type "+("`"+l+"` supplied to `"+r+"`, expected an object."))}for(var u in s)if(s.hasOwnProperty(u)){var c=e(s,u,r,i,a+"."+u,E);if(c instanceof Error)return c}return null}return i(t)}function d(e){function t(t,o,r,i,a){for(var s=0;s<e.length;s++){var l=e[s];if(null==l(t,o,r,i,a,E))return null}var p=v[i];return new n("Invalid "+p+" `"+a+"` supplied to "+("`"+r+"`."))}return Array.isArray(e)?i(t):A.thatReturnsNull}function g(){function e(e,t,o,r,i){if(!m(e[t])){var a=v[r];return new n("Invalid "+a+" `"+i+"` supplied to "+("`"+o+"`, expected a ReactNode."))}return null}return i(e)}function b(e){function t(t,o,r,i,a){var s=t[o],l=w(s);if("object"!==l){var p=v[i];return new n("Invalid "+p+" `"+a+"` of type `"+l+"` "+("supplied to `"+r+"`, expected `object`."))}for(var u in e){var c=e[u];if(c){var f=c(s,u,r,i,a+"."+u,E);if(f)return f}}return null}return i(t)}function m(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(m);if(null===e||k.isValidElement(e))return!0;var t=_(e);if(!t)return!1;var o,r=t.call(e);if(t!==e.entries){for(;!(o=r.next()).done;)if(!m(o.value))return!1}else for(;!(o=r.next()).done;){var n=o.value;if(n&&!m(n[1]))return!1}return!0;default:return!1}}function x(e,t){return"symbol"===e||("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}function w(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":x(t,e)?"symbol":t}function h(e){var t=w(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function y(e){return e.constructor&&e.constructor.name?e.constructor.name:P}var k=o(10),v=o(24),E=o(27),A=o(13),_=o(17),P=(o(12),"<<anonymous>>"),j={array:a("array"),bool:a("boolean"),func:a("function"),number:a("number"),object:a("object"),string:a("string"),symbol:a("symbol"),any:s(),arrayOf:l,element:p(),instanceOf:u,node:g(),objectOf:f,oneOf:c,oneOfType:d,shape:b};n.prototype=Error.prototype,e.exports=j},function(e,t){"use strict";var o="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";e.exports=o},function(e,t){"use strict";e.exports="15.4.2"},function(e,t,o){"use strict";function r(e){return i.isValidElement(e)?void 0:n("143"),e}var n=o(8),i=o(10);o(9);e.exports=r},function(e,t,o){var r=o(31);"string"==typeof r&&(r=[[e.id,r,""]]);o(33)(r,{});r.locals&&(e.exports=r.locals)},function(e,t,o){t=e.exports=o(32)(),t.push([e.id,"@charset \"UTF-8\";.swagger-ui html{box-sizing:border-box}.swagger-ui *,.swagger-ui :after,.swagger-ui :before{box-sizing:inherit}.swagger-ui body{margin:0;background:#fafafa}.swagger-ui .wrapper{width:100%;max-width:1460px;margin:0 auto;padding:0 20px}.swagger-ui .opblock-tag-section{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.swagger-ui .opblock-tag{display:-webkit-box;display:-ms-flexbox;display:flex;padding:10px 20px 10px 10px;cursor:pointer;-webkit-transition:all .2s;transition:all .2s;border-bottom:1px solid rgba(59,65,81,.3);-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .opblock-tag:hover{background:rgba(0,0,0,.02)}.swagger-ui .opblock-tag{font-size:24px;margin:0 0 5px;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .opblock-tag.no-desc span{-webkit-box-flex:1;-ms-flex:1;flex:1}.swagger-ui .opblock-tag svg{-webkit-transition:all .4s;transition:all .4s}.swagger-ui .opblock-tag small{font-size:14px;font-weight:400;padding:0 10px;-webkit-box-flex:1;-ms-flex:1;flex:1;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .parаmeter__type{font-size:12px;padding:5px 0;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .view-line-link{position:relative;top:3px;width:20px;margin:0 5px;cursor:pointer;-webkit-transition:all .5s;transition:all .5s}.swagger-ui .opblock{margin:0 0 15px;border:1px solid #000;border-radius:4px;box-shadow:0 0 3px rgba(0,0,0,.19)}.swagger-ui .opblock.is-open .opblock-summary{border-bottom:1px solid #000}.swagger-ui .opblock .opblock-section-header{padding:8px 20px;background:hsla(0,0%,100%,.8);box-shadow:0 1px 2px rgba(0,0,0,.1)}.swagger-ui .opblock .opblock-section-header,.swagger-ui .opblock .opblock-section-header label{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .opblock .opblock-section-header label{font-size:12px;font-weight:700;margin:0;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .opblock .opblock-section-header label span{padding:0 10px 0 0}.swagger-ui .opblock .opblock-section-header h4{font-size:14px;margin:0;-webkit-box-flex:1;-ms-flex:1;flex:1;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .opblock .opblock-summary-method{font-size:14px;font-weight:700;min-width:80px;padding:6px 15px;text-align:center;border-radius:3px;background:#000;text-shadow:0 1px 0 rgba(0,0,0,.1);font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .opblock .opblock-summary-path,.swagger-ui .opblock .opblock-summary-path__deprecated{font-size:16px;display:-webkit-box;display:-ms-flexbox;display:flex;padding:0 10px;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .opblock .opblock-summary-path .view-line-link,.swagger-ui .opblock .opblock-summary-path__deprecated .view-line-link{position:relative;top:2px;width:0;margin:0;cursor:pointer;-webkit-transition:all .5s;transition:all .5s}.swagger-ui .opblock .opblock-summary-path:hover .view-line-link,.swagger-ui .opblock .opblock-summary-path__deprecated:hover .view-line-link{width:18px;margin:0 5px}.swagger-ui .opblock .opblock-summary-path__deprecated{text-decoration:line-through}.swagger-ui .opblock .opblock-summary-description{font-size:13px;-webkit-box-flex:1;-ms-flex:1;flex:1;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .opblock .opblock-summary{display:-webkit-box;display:-ms-flexbox;display:flex;padding:5px;cursor:pointer;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .opblock.opblock-post{border-color:#49cc90;background:rgba(73,204,144,.1)}.swagger-ui .opblock.opblock-post .opblock-summary-method{background:#49cc90}.swagger-ui .opblock.opblock-post .opblock-summary{border-color:#49cc90}.swagger-ui .opblock.opblock-put{border-color:#fca130;background:rgba(252,161,48,.1)}.swagger-ui .opblock.opblock-put .opblock-summary-method{background:#fca130}.swagger-ui .opblock.opblock-put .opblock-summary{border-color:#fca130}.swagger-ui .opblock.opblock-delete{border-color:#f93e3e;background:rgba(249,62,62,.1)}.swagger-ui .opblock.opblock-delete .opblock-summary-method{background:#f93e3e}.swagger-ui .opblock.opblock-delete .opblock-summary{border-color:#f93e3e}.swagger-ui .opblock.opblock-get{border-color:#61affe;background:rgba(97,175,254,.1)}.swagger-ui .opblock.opblock-get .opblock-summary-method{background:#61affe}.swagger-ui .opblock.opblock-get .opblock-summary{border-color:#61affe}.swagger-ui .opblock.opblock-patch{border-color:#50e3c2;background:rgba(80,227,194,.1)}.swagger-ui .opblock.opblock-patch .opblock-summary-method{background:#50e3c2}.swagger-ui .opblock.opblock-patch .opblock-summary{border-color:#50e3c2}.swagger-ui .opblock.opblock-head{border-color:#9012fe;background:rgba(144,18,254,.1)}.swagger-ui .opblock.opblock-head .opblock-summary-method{background:#9012fe}.swagger-ui .opblock.opblock-head .opblock-summary{border-color:#9012fe}.swagger-ui .opblock.opblock-options{border-color:#0d5aa7;background:rgba(13,90,167,.1)}.swagger-ui .opblock.opblock-options .opblock-summary-method{background:#0d5aa7}.swagger-ui .opblock.opblock-options .opblock-summary{border-color:#0d5aa7}.swagger-ui .opblock.opblock-deprecated{opacity:.6;border-color:#ebebeb;background:hsla(0,0%,92%,.1)}.swagger-ui .opblock.opblock-deprecated .opblock-summary-method{background:#ebebeb}.swagger-ui .opblock.opblock-deprecated .opblock-summary{border-color:#ebebeb}.swagger-ui .opblock .opblock-schemes{padding:8px 20px}.swagger-ui .opblock .opblock-schemes .schemes-title{padding:0 10px 0 0}.swagger-ui .tab{display:-webkit-box;display:-ms-flexbox;display:flex;margin:20px 0 10px;padding:0;list-style:none}.swagger-ui .tab li{font-size:12px;min-width:100px;min-width:90px;padding:0;cursor:pointer;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .tab li:first-of-type{position:relative;padding-left:0}.swagger-ui .tab li:first-of-type:after{position:absolute;top:0;right:6px;width:1px;height:100%;content:\"\";background:rgba(0,0,0,.2)}.swagger-ui .tab li.active{font-weight:700}.swagger-ui .opblock-description-wrapper,.swagger-ui .opblock-title_normal{padding:15px 20px}.swagger-ui .opblock-description-wrapper,.swagger-ui .opblock-description-wrapper h4,.swagger-ui .opblock-title_normal,.swagger-ui .opblock-title_normal h4{font-size:12px;margin:0 0 5px;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .opblock-description-wrapper p,.swagger-ui .opblock-title_normal p{font-size:14px;margin:0;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .execute-wrapper{padding:20px;text-align:right}.swagger-ui .execute-wrapper .btn{width:100%;padding:8px 40px}.swagger-ui .body-param-options{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.swagger-ui .body-param-options .body-param-edit{padding:10px 0}.swagger-ui .body-param-options label{padding:8px 0}.swagger-ui .body-param-options label select{margin:3px 0 0}.swagger-ui .responses-inner{padding:20px}.swagger-ui .responses-inner h4,.swagger-ui .responses-inner h5{font-size:12px;margin:10px 0 5px;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .response-col_status{font-size:14px;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .response-col_status .response-undocumented{font-size:11px;font-family:Source Code Pro,monospace;font-weight:600;color:#999}.swagger-ui .response-col_description__inner span{font-size:12px;font-style:italic;display:block;margin:10px 0;padding:10px;border-radius:4px;background:#41444e;font-family:Source Code Pro,monospace;font-weight:600;color:#fff}.swagger-ui .response-col_description__inner span p{margin:0}.swagger-ui .opblock-body pre{font-size:12px;margin:0;padding:10px;white-space:pre-wrap;border-radius:4px;background:#41444e;font-family:Source Code Pro,monospace;font-weight:600;color:#fff}.swagger-ui .opblock-body pre span{color:#fff!important}.swagger-ui .scheme-container{margin:0 0 20px;padding:30px 0;background:#fff;box-shadow:0 1px 2px 0 rgba(0,0,0,.15)}.swagger-ui .scheme-container .schemes{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .scheme-container .schemes>label{font-size:12px;font-weight:700;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;margin:-20px 15px 0 0;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .scheme-container .schemes>label select{min-width:130px;text-transform:uppercase}.swagger-ui .loading-container{padding:40px 0 60px}.swagger-ui .loading-container .loading{position:relative}.swagger-ui .loading-container .loading:after{font-size:10px;font-weight:700;position:absolute;top:50%;left:50%;content:\"loading\";-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);text-transform:uppercase;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .loading-container .loading:before{position:absolute;top:50%;left:50%;display:block;width:60px;height:60px;margin:-30px;content:\"\";-webkit-animation:rotation 1s infinite linear,opacity .5s;animation:rotation 1s infinite linear,opacity .5s;opacity:1;border:2px solid rgba(85,85,85,.1);border-top-color:rgba(0,0,0,.6);border-radius:100%;-webkit-backface-visibility:hidden;backface-visibility:hidden}@-webkit-keyframes rotation{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes rotation{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@-webkit-keyframes blinker{50%{opacity:0}}@keyframes blinker{50%{opacity:0}}.swagger-ui .btn{font-size:14px;font-weight:700;padding:5px 23px;-webkit-transition:all .3s;transition:all .3s;border:2px solid #888;border-radius:4px;background:transparent;box-shadow:0 1px 2px rgba(0,0,0,.1);font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .btn[disabled]{cursor:not-allowed;opacity:.3}.swagger-ui .btn:hover{box-shadow:0 0 5px rgba(0,0,0,.3)}.swagger-ui .btn.cancel{border-color:#ff6060;font-family:Titillium Web,sans-serif;color:#ff6060}.swagger-ui .btn.authorize{line-height:1;display:inline;color:#49cc90;border-color:#49cc90}.swagger-ui .btn.authorize span{float:left;padding:4px 20px 0 0}.swagger-ui .btn.authorize svg{fill:#49cc90}.swagger-ui .btn.execute{-webkit-animation:pulse 2s infinite;animation:pulse 2s infinite;color:#fff;border-color:#4990e2}@-webkit-keyframes pulse{0%{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,.8)}70%{box-shadow:0 0 0 5px rgba(73,144,226,0)}to{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,0)}}@keyframes pulse{0%{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,.8)}70%{box-shadow:0 0 0 5px rgba(73,144,226,0)}to{color:#fff;background:#4990e2;box-shadow:0 0 0 0 rgba(73,144,226,0)}}.swagger-ui .btn-group{display:-webkit-box;display:-ms-flexbox;display:flex;padding:30px}.swagger-ui .btn-group .btn{-webkit-box-flex:1;-ms-flex:1;flex:1}.swagger-ui .btn-group .btn:first-child{border-radius:4px 0 0 4px}.swagger-ui .btn-group .btn:last-child{border-radius:0 4px 4px 0}.swagger-ui .authorization__btn{padding:0 10px;border:none;background:none}.swagger-ui .authorization__btn.locked{opacity:1}.swagger-ui .authorization__btn.unlocked{opacity:.4}.swagger-ui .expand-methods,.swagger-ui .expand-operation{border:none;background:none}.swagger-ui .expand-methods svg,.swagger-ui .expand-operation svg{width:20px;height:20px}.swagger-ui .expand-methods{padding:0 10px}.swagger-ui .expand-methods:hover svg{fill:#444}.swagger-ui .expand-methods svg{-webkit-transition:all .3s;transition:all .3s;fill:#777}.swagger-ui button{cursor:pointer;outline:none}.swagger-ui select{font-size:14px;font-weight:700;padding:5px 40px 5px 10px;border:2px solid #41444e;border-radius:4px;background:#f7f7f7 url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyMCAyMCI+ICAgIDxwYXRoIGQ9Ik0xMy40MTggNy44NTljLjI3MS0uMjY4LjcwOS0uMjY4Ljk3OCAwIC4yNy4yNjguMjcyLjcwMSAwIC45NjlsLTMuOTA4IDMuODNjLS4yNy4yNjgtLjcwNy4yNjgtLjk3OSAwbC0zLjkwOC0zLjgzYy0uMjctLjI2Ny0uMjctLjcwMSAwLS45NjkuMjcxLS4yNjguNzA5LS4yNjguOTc4IDBMMTAgMTFsMy40MTgtMy4xNDF6Ii8+PC9zdmc+) right 10px center no-repeat;background-size:20px;box-shadow:0 1px 2px 0 rgba(0,0,0,.25);font-family:Titillium Web,sans-serif;color:#3b4151;-webkit-appearance:none;-moz-appearance:none;appearance:none}.swagger-ui select[multiple]{margin:5px 0;padding:5px;background:#f7f7f7}.swagger-ui .opblock-body select{min-width:230px}.swagger-ui label{font-size:12px;font-weight:700;margin:0 0 5px;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui input[type=email],.swagger-ui input[type=password],.swagger-ui input[type=search],.swagger-ui input[type=text]{min-width:100px;margin:5px 0;padding:8px 10px;border:1px solid #d9d9d9;border-radius:4px;background:#fff}.swagger-ui input[type=email].invalid,.swagger-ui input[type=password].invalid,.swagger-ui input[type=search].invalid,.swagger-ui input[type=text].invalid{-webkit-animation:shake .4s 1;animation:shake .4s 1;border-color:#f93e3e;background:#feebeb}@-webkit-keyframes shake{10%,90%{-webkit-transform:translate3d(-1px,0,0);transform:translate3d(-1px,0,0)}20%,80%{-webkit-transform:translate3d(2px,0,0);transform:translate3d(2px,0,0)}30%,50%,70%{-webkit-transform:translate3d(-4px,0,0);transform:translate3d(-4px,0,0)}40%,60%{-webkit-transform:translate3d(4px,0,0);transform:translate3d(4px,0,0)}}@keyframes shake{10%,90%{-webkit-transform:translate3d(-1px,0,0);transform:translate3d(-1px,0,0)}20%,80%{-webkit-transform:translate3d(2px,0,0);transform:translate3d(2px,0,0)}30%,50%,70%{-webkit-transform:translate3d(-4px,0,0);transform:translate3d(-4px,0,0)}40%,60%{-webkit-transform:translate3d(4px,0,0);transform:translate3d(4px,0,0)}}.swagger-ui textarea{font-size:12px;width:100%;min-height:280px;padding:10px;border:none;border-radius:4px;outline:none;background:hsla(0,0%,100%,.8);font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui textarea:focus{border:2px solid #61affe}.swagger-ui textarea.curl{font-size:12px;min-height:100px;margin:0;padding:10px;resize:none;border-radius:4px;background:#41444e;font-family:Source Code Pro,monospace;font-weight:600;color:#fff}.swagger-ui .checkbox{padding:5px 0 10px;-webkit-transition:opacity .5s;transition:opacity .5s;color:#333}.swagger-ui .checkbox label{display:-webkit-box;display:-ms-flexbox;display:flex}.swagger-ui .checkbox p{font-weight:400!important;font-style:italic;margin:0!important;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .checkbox input[type=checkbox]{display:none}.swagger-ui .checkbox input[type=checkbox]+label>.item{position:relative;top:3px;display:inline-block;width:16px;height:16px;margin:0 8px 0 0;padding:5px;cursor:pointer;border-radius:1px;background:#e8e8e8;box-shadow:0 0 0 2px #e8e8e8;-webkit-box-flex:0;-ms-flex:none;flex:none}.swagger-ui .checkbox input[type=checkbox]+label>.item:active{-webkit-transform:scale(.9);transform:scale(.9)}.swagger-ui .checkbox input[type=checkbox]:checked+label>.item{background:#e8e8e8 url(\"data:image/svg+xml;charset=utf-8,%3Csvg width='10' height='8' viewBox='3 7 10 8' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%2341474E' fill-rule='evenodd' d='M6.333 15L3 11.667l1.333-1.334 2 2L11.667 7 13 8.333z'/%3E%3C/svg%3E\") 50% no-repeat}.swagger-ui .dialog-ux{position:fixed;z-index:9999;top:0;right:0;bottom:0;left:0}.swagger-ui .dialog-ux .backdrop-ux{position:fixed;top:0;right:0;bottom:0;left:0;background:rgba(0,0,0,.8)}.swagger-ui .dialog-ux .modal-ux{position:absolute;z-index:9999;top:50%;left:50%;width:100%;min-width:300px;max-width:650px;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);border:1px solid #ebebeb;border-radius:4px;background:#fff;box-shadow:0 10px 30px 0 rgba(0,0,0,.2)}.swagger-ui .dialog-ux .modal-ux-content{overflow-y:auto;max-height:540px;padding:20px}.swagger-ui .dialog-ux .modal-ux-content p{font-size:12px;margin:0 0 5px;color:#41444e;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .dialog-ux .modal-ux-content h4{font-size:18px;font-weight:600;margin:15px 0 0;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .dialog-ux .modal-ux-header{display:-webkit-box;display:-ms-flexbox;display:flex;padding:12px 0;border-bottom:1px solid #ebebeb;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .dialog-ux .modal-ux-header .close-modal{padding:0 10px;border:none;background:none;-webkit-appearance:none;-moz-appearance:none;appearance:none}.swagger-ui .dialog-ux .modal-ux-header h3{font-size:20px;font-weight:600;margin:0;padding:0 20px;-webkit-box-flex:1;-ms-flex:1;flex:1;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .model{font-size:12px;font-weight:300;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .model-toggle{font-size:10px;position:relative;top:6px;display:inline-block;margin:auto .3em;cursor:pointer;-webkit-transition:-webkit-transform .15s ease-in;transition:-webkit-transform .15s ease-in;transition:transform .15s ease-in;transition:transform .15s ease-in,-webkit-transform .15s ease-in;-webkit-transform:rotate(90deg);transform:rotate(90deg);-webkit-transform-origin:50% 50%;transform-origin:50% 50%}.swagger-ui .model-toggle.collapsed{-webkit-transform:rotate(0deg);transform:rotate(0deg)}.swagger-ui .model-toggle:after{display:block;width:20px;height:20px;content:\"\";background:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z'/%3E%3C/svg%3E\") 50% no-repeat;background-size:100%}.swagger-ui .model-jump-to-path{position:relative;cursor:pointer}.swagger-ui .model-jump-to-path .view-line-link{position:absolute;top:-.4em;cursor:pointer}.swagger-ui .model-title{position:relative}.swagger-ui .model-title:hover .model-hint{visibility:visible}.swagger-ui .model-hint{position:absolute;top:-1.8em;visibility:hidden;padding:.1em .5em;white-space:nowrap;color:#ebebeb;border-radius:4px;background:rgba(0,0,0,.7)}.swagger-ui section.models{margin:30px 0;border:1px solid rgba(59,65,81,.3);border-radius:4px}.swagger-ui section.models.is-open{padding:0 0 20px}.swagger-ui section.models.is-open h4{margin:0 0 5px;border-bottom:1px solid rgba(59,65,81,.3)}.swagger-ui section.models.is-open h4 svg{-webkit-transform:rotate(90deg);transform:rotate(90deg)}.swagger-ui section.models h4{font-size:16px;display:-webkit-box;display:-ms-flexbox;display:flex;margin:0;padding:10px 20px 10px 10px;cursor:pointer;-webkit-transition:all .2s;transition:all .2s;font-family:Titillium Web,sans-serif;color:#777;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui section.models h4 svg{-webkit-transition:all .4s;transition:all .4s}.swagger-ui section.models h4 span{-webkit-box-flex:1;-ms-flex:1;flex:1}.swagger-ui section.models h4:hover{background:rgba(0,0,0,.02)}.swagger-ui section.models h5{font-size:16px;margin:0 0 10px;font-family:Titillium Web,sans-serif;color:#777}.swagger-ui section.models .model-jump-to-path{position:relative;top:5px}.swagger-ui section.models .model-container{margin:0 20px 15px;-webkit-transition:all .5s;transition:all .5s;border-radius:4px;background:rgba(0,0,0,.05)}.swagger-ui section.models .model-container:hover{background:rgba(0,0,0,.07)}.swagger-ui section.models .model-container:first-of-type{margin:20px}.swagger-ui section.models .model-container:last-of-type{margin:0 20px}.swagger-ui section.models .model-box{background:none}.swagger-ui .model-box{padding:10px;border-radius:4px;background:rgba(0,0,0,.1)}.swagger-ui .model-box .model-jump-to-path{position:relative;top:4px}.swagger-ui .model-title{font-size:16px;font-family:Titillium Web,sans-serif;color:#555}.swagger-ui span>span.model,.swagger-ui span>span.model .brace-close{padding:0 0 0 10px}.swagger-ui .prop-type{color:#55a}.swagger-ui .prop-enum{display:block}.swagger-ui .prop-format{color:#999}.swagger-ui table{width:100%;padding:0 10px;border-collapse:collapse}.swagger-ui table.model tbody tr td{padding:0;vertical-align:top}.swagger-ui table.model tbody tr td:first-of-type{width:100px;padding:0}.swagger-ui table.headers td{font-size:12px;font-weight:300;vertical-align:middle;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui table tbody tr td{padding:10px 0 0;vertical-align:top}.swagger-ui table tbody tr td:first-of-type{width:20%;padding:10px 0}.swagger-ui table thead tr td,.swagger-ui table thead tr th{font-size:12px;font-weight:700;padding:12px 0;text-align:left;border-bottom:1px solid rgba(59,65,81,.2);font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .parameters-col_description p{font-size:14px;margin:0;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .parameters-col_description input[type=text]{width:100%;max-width:340px}.swagger-ui .parameter__name{font-size:16px;font-weight:400;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .parameter__name.required{font-weight:700}.swagger-ui .parameter__name.required:after{font-size:10px;position:relative;top:-6px;padding:5px;content:\"required\";color:rgba(255,0,0,.6)}.swagger-ui .parameter__in{font-size:12px;font-style:italic;font-family:Source Code Pro,monospace;font-weight:600;color:#888}.swagger-ui .table-container{padding:20px}.swagger-ui .topbar{padding:8px 30px;background-color:#89bf04}.swagger-ui .topbar .topbar-wrapper{-ms-flex-align:center}.swagger-ui .topbar .topbar-wrapper,.swagger-ui .topbar a{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;align-items:center}.swagger-ui .topbar a{font-size:1.5em;font-weight:700;text-decoration:none;-webkit-box-flex:1;-ms-flex:1;flex:1;-ms-flex-align:center;font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .topbar a span{margin:0;padding:0 10px}.swagger-ui .topbar .download-url-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex}.swagger-ui .topbar .download-url-wrapper input[type=text]{min-width:350px;margin:0;border:2px solid #547f00;border-radius:4px 0 0 4px;outline:none}.swagger-ui .topbar .download-url-wrapper .download-url-button{font-size:16px;font-weight:700;padding:4px 40px;border:none;border-radius:0 4px 4px 0;background:#547f00;font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .info{margin:50px 0}.swagger-ui .info hgroup.main{margin:0 0 20px}.swagger-ui .info hgroup.main a{font-size:12px}.swagger-ui .info p{font-size:14px;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .info code{padding:3px 5px;border-radius:4px;background:rgba(0,0,0,.05);font-family:Source Code Pro,monospace;font-weight:600;color:#9012fe}.swagger-ui .info a{font-size:14px;-webkit-transition:all .4s;transition:all .4s;font-family:Open Sans,sans-serif;color:#4990e2}.swagger-ui .info a:hover{color:#1f69c0}.swagger-ui .info>div{margin:0 0 5px}.swagger-ui .info .base-url{font-size:12px;font-weight:300!important;margin:0;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .info .title{font-size:36px;margin:0;font-family:Open Sans,sans-serif;color:#3b4151}.swagger-ui .info .title small{font-size:10px;position:relative;top:-5px;display:inline-block;margin:0 0 0 5px;padding:2px 4px;vertical-align:super;border-radius:57px;background:#7d8492}.swagger-ui .info .title small pre{margin:0;font-family:Titillium Web,sans-serif;color:#fff}.swagger-ui .auth-btn-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;padding:10px 0;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}.swagger-ui .auth-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-flex:1;-ms-flex:1;flex:1;-webkit-box-pack:end;-ms-flex-pack:end;justify-content:flex-end}.swagger-ui .auth-wrapper .authorize{padding-right:20px}.swagger-ui .auth-container{margin:0 0 10px;padding:10px 20px;border-bottom:1px solid #ebebeb}.swagger-ui .auth-container:last-of-type{margin:0;padding:10px 20px;border:0}.swagger-ui .auth-container h4{margin:5px 0 15px!important}.swagger-ui .auth-container .wrapper{margin:0;padding:0}.swagger-ui .auth-container input[type=password],.swagger-ui .auth-container input[type=text]{min-width:230px}.swagger-ui .auth-container .errors{font-size:12px;padding:10px;border-radius:4px;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .scopes h2{font-size:14px;font-family:Titillium Web,sans-serif;color:#3b4151}.swagger-ui .scope-def{padding:0 0 20px}.swagger-ui .errors-wrapper{margin:20px;padding:10px 20px;-webkit-animation:scaleUp .5s;animation:scaleUp .5s;border:2px solid #f93e3e;border-radius:4px;background:rgba(249,62,62,.1)}.swagger-ui .errors-wrapper .error-wrapper{margin:0 0 10px}.swagger-ui .errors-wrapper .errors h4{font-size:14px;margin:0;font-family:Source Code Pro,monospace;font-weight:600;color:#3b4151}.swagger-ui .errors-wrapper .errors small{color:#666}.swagger-ui .errors-wrapper hgroup{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.swagger-ui .errors-wrapper hgroup h4{font-size:20px;margin:0;-webkit-box-flex:1;-ms-flex:1;flex:1;font-family:Titillium Web,sans-serif;color:#3b4151}@-webkit-keyframes scaleUp{0%{-webkit-transform:scale(.8);transform:scale(.8);opacity:0}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}@keyframes scaleUp{0%{-webkit-transform:scale(.8);transform:scale(.8);opacity:0}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}",""]); },function(e,t){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var o=this[t];o[2]?e.push("@media "+o[2]+"{"+o[1]+"}"):e.push(o[1])}return e.join("")},e.i=function(t,o){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},n=0;n<this.length;n++){var i=this[n][0];"number"==typeof i&&(r[i]=!0)}for(n=0;n<t.length;n++){var a=t[n];"number"==typeof a[0]&&r[a[0]]||(o&&!a[2]?a[2]=o:o&&(a[2]="("+a[2]+") and ("+o+")"),e.push(a))}},e}},function(e,t,o){function r(e,t){for(var o=0;o<e.length;o++){var r=e[o],n=d[r.id];if(n){n.refs++;for(var i=0;i<n.parts.length;i++)n.parts[i](r.parts[i]);for(;i<r.parts.length;i++)n.parts.push(p(r.parts[i],t))}else{for(var a=[],i=0;i<r.parts.length;i++)a.push(p(r.parts[i],t));d[r.id]={id:r.id,refs:1,parts:a}}}}function n(e){for(var t=[],o={},r=0;r<e.length;r++){var n=e[r],i=n[0],a=n[1],s=n[2],l=n[3],p={css:a,media:s,sourceMap:l};o[i]?o[i].parts.push(p):t.push(o[i]={id:i,parts:[p]})}return t}function i(e,t){var o=m(),r=h[h.length-1];if("top"===e.insertAt)r?r.nextSibling?o.insertBefore(t,r.nextSibling):o.appendChild(t):o.insertBefore(t,o.firstChild),h.push(t);else{if("bottom"!==e.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");o.appendChild(t)}}function a(e){e.parentNode.removeChild(e);var t=h.indexOf(e);t>=0&&h.splice(t,1)}function s(e){var t=document.createElement("style");return t.type="text/css",i(e,t),t}function l(e){var t=document.createElement("link");return t.rel="stylesheet",i(e,t),t}function p(e,t){var o,r,n;if(t.singleton){var i=w++;o=x||(x=s(t)),r=u.bind(null,o,i,!1),n=u.bind(null,o,i,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(o=l(t),r=f.bind(null,o),n=function(){a(o),o.href&&URL.revokeObjectURL(o.href)}):(o=s(t),r=c.bind(null,o),n=function(){a(o)});return r(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;r(e=t)}else n()}}function u(e,t,o,r){var n=o?"":r.css;if(e.styleSheet)e.styleSheet.cssText=y(t,n);else{var i=document.createTextNode(n),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(i,a[t]):e.appendChild(i)}}function c(e,t){var o=t.css,r=t.media;t.sourceMap;if(r&&e.setAttribute("media",r),e.styleSheet)e.styleSheet.cssText=o;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(o))}}function f(e,t){var o=t.css,r=(t.media,t.sourceMap);r&&(o+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */");var n=new Blob([o],{type:"text/css"}),i=e.href;e.href=URL.createObjectURL(n),i&&URL.revokeObjectURL(i)}var d={},g=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},b=g(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),m=g(function(){return document.head||document.getElementsByTagName("head")[0]}),x=null,w=0,h=[];e.exports=function(e,t){t=t||{},"undefined"==typeof t.singleton&&(t.singleton=b()),"undefined"==typeof t.insertAt&&(t.insertAt="bottom");var o=n(e);return r(o,t),function(e){for(var i=[],a=0;a<o.length;a++){var s=o[a],l=d[s.id];l.refs--,i.push(l)}if(e){var p=n(e);r(p,t)}for(var a=0;a<i.length;a++){var l=i[a];if(0===l.refs){for(var u=0;u<l.parts.length;u++)l.parts[u]();delete d[l.id]}}}};var y=function(){var e=[];return function(t,o){return e[t]=o,e.filter(Boolean).join("\n")}}()},function(e,t,o){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{components:{Topbar:i.default}}};var n=o(35),i=r(n)},function(e,t,o){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var o=0;o<t.length;o++){var r=t[o];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,o,r){return o&&e(t.prototype,o),r&&e(t,r),t}}(),l=o(3),p=r(l),u=o(36),c=r(u),f=function(e){function t(e,o){n(this,t);var r=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,o));return r.onUrlChange=function(e){var t=e.target.value;r.setState({url:t})},r.downloadUrl=function(){r.props.specActions.updateUrl(r.state.url),r.props.specActions.download(r.state.url)},r.state={url:e.specSelectors.url()},r}return a(t,e),s(t,[{key:"componentWillReceiveProps",value:function(e){this.setState({url:e.specSelectors.url()})}},{key:"render",value:function(){var e=this.props,t=e.getComponent,o=e.specSelectors,r=t("Button"),n=t("Link"),i="loading"===o.loadingStatus(),a="failed"===o.loadingStatus(),s={};return a&&(s.color="red"),i&&(s.color="#aaa"),p.default.createElement("div",{className:"topbar"},p.default.createElement("div",{className:"wrapper"},p.default.createElement("div",{className:"topbar-wrapper"},p.default.createElement(n,{href:"#",title:"Swagger UX"},p.default.createElement("img",{height:"30",width:"30",src:c.default,alt:"Swagger UX"}),p.default.createElement("span",null,"swagger")),p.default.createElement("div",{className:"download-url-wrapper"},p.default.createElement("input",{className:"download-url-input",type:"text",onChange:this.onUrlChange,value:this.state.url,disabled:i,style:s}),p.default.createElement(r,{className:"download-url-button",onClick:this.downloadUrl},"Explore")))))}}]),t}(p.default.Component);t.default=f,f.propTypes={specSelectors:l.PropTypes.object.isRequired,specActions:l.PropTypes.object.isRequired,getComponent:l.PropTypes.func.isRequired}},function(e,t){e.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAqRJREFUeNrEVz1s00AUfnGXii5maMXoEUEHVwIpEkPNgkBdMnQoU5ytiKHJwpp2Q2JIO8DCUDOxIJFIVOoWZyJSh3pp1Q2PVVlcCVBH3ufeVZZ9Zye1Ay86nXV+ue/9fO/lheg/Se02X1rvksmbnTiKvuxQMBNgBnN4a/LCbmnUAP6JV58NCUsBC8CuAJxGPF47OgNqBaA93tolUhnx6jC4NxGwyOEwlccyAs+3kwdzKq0HDn2vEBTi8J2XpyMaywNDE157BhXUE3zJhlq8GKq+Zd2zaWHepPA8oN9XkfLmRdOiJV4XUUg/IyWncLjCYY/SHndV2u7zHr3bPKZtdxgboJOnthvrfGj/oMf3G0r7JVmNlLfKklmrt2MvvcNO7LFOhoFHfuAJI5o6ta10jpt5CQLgwXhXG2YIwvu+34qf78ybOjWTnWwkgR36d7JqJOrW0hHmNrKg9xhiS4+1jFmrxymh03B0w+6kURIAu3yHtOD5oaUNojMnGgbcctNvwdAnyxvxRR+/vaJnjzbpzcZX+nN1SdGv85i9eH8w3qPO+mdm/y4dnQ1iI8Fq6Nf4cxL6GWSjiFDSs0VRnxC5g0xSB2cgHpaseTxfqOv5uoHkNQ6Ha/N1Yz9mNMppEkEkYKj79q6uCq4bCHcSX3fJ0Vk/k9siASjCm1N6gZH6Ec9IXt2WkFES2K/ixoIyktJPAu/ptOA1SgO5zqtr6KASJPF0nMV8dgMsRhRPOcMwqQAOoi0VAIMLAEWJ6YYC1c8ibj1GP51RqwzYwZVMHQuvOzMCBUtb2tGHx5NAdLKqp5AX7Ng4d+Zi8AGDI9z1ijx9yaCH04y3GCP2S+QcvaGl+pcxyUBvinFlawoDQjHSelX8hQEoIrAq8p/mgC88HOS1YCl/BRgAmiD/1gn6Nu8AAAAASUVORK5CYII="}])}); //# sourceMappingURL=swagger-ui-standalone-preset.js.map
proto/data-refining/front/workdir/components/includes/ZBootstrap.js
cttgroup/oceanhub
import React from 'react' import PropTypes from 'prop-types' import { FormControl, FormGroup, HelpBlock, Button, ControlLabel, Checkbox, } from 'react-bootstrap' export class ZSelect extends React.Component { constructor(props) { super(props) this.options = [] this.state = { select: 'norv-small' } this.handleChange = this.handleChange.bind(this) // Forming options list array this.props.options.forEach(function(element, key) { this.options.push( <option key={key} value={element.value} selected={element.selected} > {element.value} </option> ) }.bind(this)) } handleChange(obj) { // Buble date changes to the parent component this.props.handleStateKeyValueUpdate(this.props.name, obj.target.value) this.setState({value: obj.target.value}) } render() { return (<div> <FormGroup controlId="formControlsSelect"> <ControlLabel>{this.props.title}</ControlLabel> <FormControl componentClass="select" defaultValue={this.props.defaultValue} value={this.props.value} placeholder="select" onChange={this.handleChange} > {this.options} </FormControl> </FormGroup> </div>) } } export class ZFieldGroup extends React.Component { constructor(props) { super(props) this.handleChange = this.handleChange.bind(this) } handleChange(obj) { let func = this.props._handleChange if (typeof func === 'function') { func(this.props.id, obj.target.value) } } render() { return ( <FormGroup controlId={this.props.id}> <ControlLabel>{this.props.label}</ControlLabel> <FormControl value={this.props.value} type={this.props.type} placeholder={this.props.placeholder} onChange={this.handleChange} /> {this.props.help && <HelpBlock>{this.props.help}</HelpBlock>} </FormGroup> ) } } export class ZCheckbox extends React.Component { constructor(props) { super(props) this.handleChange = this.handleChange.bind(this) } handleChange(obj) { let options = this.props.options const find = (value) => options.find((element, index, array) => { if (element.value == value) { console.log('index > ', index, element); array[index].checked = !array[index].checked } }) find(obj.target.value) this.props.handleStateKeyValueUpdate('characteristics', options) } render() { // Forming checkbox list array let rows = [] this.props.options.forEach(function(element, key) { rows.push( <Checkbox key={key} value={element.value} onChange={this.handleChange} checked={element.checked} > {element.label} </Checkbox> ) }.bind(this)) return ( <FormGroup> <ControlLabel>{this.props.title}</ControlLabel> {rows} </FormGroup> ) } } ZCheckbox.propTypes = { handleStateKeyValueUpdate: PropTypes.func, } export class ZSingleCheckbox extends React.Component { constructor(props) { super(props) this.options = [] this.state = { checked: this.props.checked, } this.handleChange = this.handleChange.bind(this) } handleChange(obj) { let func = this.props._handleChange if (typeof func === 'function') { func(this.props.id, obj.target.checked) } } render() { return ( <Checkbox key={this.props.id} checked={this.props.checked} onChange={this.handleChange} > {this.props.lable} </Checkbox> ) } } export class ZText extends React.Component { constructor(props) { super(props) this.state = { value: '', } this.getValidationState = this.getValidationState.bind(this) this.handleChange = this.handleChange.bind(this) } handleChange(obj) { let func = this.props._handleChange if (typeof func === 'function') { func(this.props.name, obj.target.value) } this.setState({ value: obj.target.value }) } getValidationState() { const length = this.state.value.length; if (length > 10) return 'success'; else if (length > 5) return 'warning'; else if (length > 0) return 'error'; } render() { return ( <FormGroup controlId={this.props.name} // validationState={this.getValidationState()} > <ControlLabel>{this.props.label}</ControlLabel> <FormControl type="text" value={this.state.value} placeholder="Введите текст" onChange={this.handleChange} /> <FormControl.Feedback /> <HelpBlock>{this.props.help}</HelpBlock> </FormGroup> ) } } const FormExample = React.createClass({ render() { return ( <form> </form> ); } });
files/rxjs/2.3.8/rx.lite.compat.js
megawac/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 = (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; }; // 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; } // 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 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; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var s = state; var id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; }(Scheduler.prototype)); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * 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)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { 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; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called '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); }); }); }; 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; }); }; /** * 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); }); }; /** * 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(); }); }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each 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)); }); }; /** * 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 fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation){ event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch(event.type){ case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return 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); } }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return !selector ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish(null).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return !selector ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue). refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return !selector ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @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); }) }; /** * 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); }); }; /** * 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(); }); }); }; /** * 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))); }); }; var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.subject.distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } previousShouldFire = results.shouldFire; }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); this.subject.onNext(false); return subscription; } function PausableBufferedObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the 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)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
src/routes/home/Home.js
devcharleneg/twitter-react-app
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Twit from 'twit'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Home.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 HomeTimeline from '../../components/Tweet/HomeTimeline'; import SearchTimeline from '../../components/Tweet/SearchTimeline'; import UserInfo from '../../components/Profile/UserInfo'; class Home extends React.Component { static propTypes = { title: PropTypes.string.isRequired }; constructor(props) { super(props); this.state = { tweets: [], tweetDiv: null, searchTweetText: 'ReactJS', searchTimelineDiv: null, showHomeTimeline: false } this._onSeachTweetTextChange = this._onSeachTweetTextChange.bind(this); } _onSeachTweetTextChange(e) { var text = e.target.value; this.setState({searchTweetText: text}); } _getSearchTweets(e) { var e = e ? e.preventDefault() : ''; var tweetDiv = []; tweetDiv.push(<SearchTimeline query={this.state.searchTweetText} key={0}/>); this.setState({searchTimelineDiv: tweetDiv}); } componentDidMount() { if(Session.getAccessToken() && Session.getAccessTokenSecret()) { this.setState({showHomeTimeline: true}); } else { this.setState({showHomeTimeline: false}); var tweetDiv = []; tweetDiv.push(<SearchTimeline query={this.state.searchTweetText} key={0}/>); this.setState({searchTimelineDiv: tweetDiv}); } } render() { return ( <div className={s.root}> <div className={s.container}> { this.state.showHomeTimeline ? <Row> <Col sm={4}> <UserInfo /> </Col> <Col sm={8}> <HomeTimeline /> </Col> </Row> : this.state.searchTimelineDiv } </div> </div> ); } } export default withStyles(s)(Home);
src/components/LittleLight.js
MrRandol/littleLight
/********************** REDUX COMPONENT **********************/ import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as Actions from '../actions'; function mapStateToProps(state) { return {loading: state.loading.loading, state: state}; } function mapDispatchToProps(dispatch) { return bindActionCreators(Actions, dispatch); } /****************** REACT IMPORTS ******************/ import React from 'react'; import { View, StatusBar, BackHandler } from 'react-native'; // Global wrapper to catch exceptions. import * as ErrorHandler from '../utils/errorHandler'; /***************** CUSTOM IMPORTS ******************/ import T from 'i18n-react'; var styles = require('../styles/LittleLight'); import SplashScreen from './SplashScreen'; import ItemsManager from './itemsManager/ItemsManager'; class LittleLight extends React.Component { constructor(props) { super(props); this.state = { locale: 'en' } var localeTexts; switch(this.state.locale) { case 'fr': localeTexts = require('../i18n/fr.json') break; case 'en': default: localeTexts = require('../i18n/en.json') } T.setTexts(localeTexts); } //Global backbutton handler. // Direty but only way I found for now ... componentWillMount() { var self = this; BackHandler.addEventListener('hardwareBackPress', function() { if (self.props.state.loading.currentSection === 'itemsManager') { switch (self.props.state.itemsManager.currentView.name) { case 'GuardianOverview': return false; case 'ItemTypeManager': self.props.switchView('GuardianOverview'); return true; default: return false; } } return false; }); } render() { var content; if (this.props.loading !== false) { content = ( <SplashScreen locale={this.state.locale} style={{flex: 1}} /> ); } else { content = ( <ItemsManager style={{flex: 1}} /> ); } return ( <View style={styles.container}> <StatusBar hidden={true} /> { content } </View> ); } } export default connect(mapStateToProps, mapDispatchToProps)(LittleLight);
react/src/components/footer.js
jasonrhodes/how-to-react
import React from 'react' export default (props) => { return <footer><a href={props.url}>Here is a link</a></footer> }
src/components/common/svg-icons/action/lock.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionLock = (props) => ( <SvgIcon {...props}> <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/> </SvgIcon> ); ActionLock = pure(ActionLock); ActionLock.displayName = 'ActionLock'; ActionLock.muiName = 'SvgIcon'; export default ActionLock;
packages/react-reconciler/src/forks/ReactFiberHostConfig.fabric.js
chenglou/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from 'react-native-renderer/src/ReactFabricHostConfig';
examples/src/components/DisabledUpsellOptions.js
oluckyman/react-select
import React from 'react'; import Select from 'react-select'; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var DisabledUpsellOptions = React.createClass({ displayName: 'DisabledUpsellOptions', propTypes: { label: React.PropTypes.string, }, onLabelClick: function (data, event) { console.log(data, event); }, renderLink: function() { return <a style={{ marginLeft: 5 }} href="/upgrade" target="_blank">Upgrade here!</a>; }, renderOption: function(option) { return <span>{option.label} {option.link} </span>; }, render: function() { var ops = [ { label: 'Basic customer support', value: 'basic' }, { label: 'Premium customer support', value: 'premium' }, { label: 'Pro customer support', value: 'pro', disabled: true, link: this.renderLink() }, ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select onOptionLabelClick={this.onLabelClick} placeholder="Select your support level" options={ops} optionRenderer={this.renderOption} onChange={logChange} /> </div> ); } }); module.exports = DisabledUpsellOptions;
src/utils/CustomPropTypes.js
pieter-lazzaro/react-bootstrap
import React from 'react'; const ANONYMOUS = '<<anonymous>>'; const CustomPropTypes = { isRequiredForA11y(propType){ return function(props, propName, componentName){ if (props[propName] === null) { return new Error( 'The prop `' + propName + '` is required to make ' + componentName + ' accessible ' + 'for users using assistive technologies such as screen readers `' ); } return propType(props, propName, componentName); }; }, /** * Checks whether a prop provides a DOM element * * The element can be provided in two forms: * - Directly passed * - Or passed an object that has a `render` method * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ mountable: createMountableChecker(), /** * Checks whether a prop provides a type of element. * * The type of element can be provided in two forms: * - tag name (string) * - a return value of React.createClass(...) * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ elementType: createElementTypeChecker(), /** * Checks whether a prop matches a key of an associated object * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ keyOf: createKeyOfChecker, /** * Checks if only one of the listed properties is in use. An error is given * if multiple have a value * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ singlePropFrom: createSinglePropFromChecker, all }; function errMsg(props, propName, componentName, msgContinuation) { return `Invalid prop '${propName}' of value '${props[propName]}'` + ` supplied to '${componentName}'${msgContinuation}`; } /** * Create chain-able isRequired validator * * Largely copied directly from: * https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94 */ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { if (isRequired) { return new Error( `Required prop '${propName}' was not specified in '${componentName}'.` ); } } else { return validate(props, propName, componentName); } } let chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createMountableChecker() { function validate(props, propName, componentName) { if (typeof props[propName] !== 'object' || typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) { return new Error( errMsg(props, propName, componentName, ', expected a DOM element or an object that has a `render` method') ); } } return createChainableTypeChecker(validate); } function createKeyOfChecker(obj) { function validate(props, propName, componentName) { let propValue = props[propName]; if (!obj.hasOwnProperty(propValue)) { let valuesString = JSON.stringify(Object.keys(obj)); return new Error( errMsg(props, propName, componentName, `, expected one of ${valuesString}.`) ); } } return createChainableTypeChecker(validate); } function createSinglePropFromChecker(arrOfProps) { function validate(props, propName, componentName) { const usedPropCount = arrOfProps .map(listedProp => props[listedProp]) .reduce((acc, curr) => acc + (curr !== undefined ? 1 : 0), 0); if (usedPropCount > 1) { const [first, ...others] = arrOfProps; const message = `${others.join(', ')} and ${first}`; return new Error( `Invalid prop '${propName}', only one of the following ` + `may be provided: ${message}` ); } } return validate; } function all(propTypes) { if (propTypes === undefined) { throw new Error('No validations provided'); } if (!(propTypes instanceof Array)) { throw new Error('Invalid argument must be an array'); } if (propTypes.length === 0) { throw new Error('No validations provided'); } return function(props, propName, componentName) { for(let i = 0; i < propTypes.length; i++) { let result = propTypes[i](props, propName, componentName); if (result !== undefined && result !== null) { return result; } } }; } function createElementTypeChecker() { function validate(props, propName, componentName) { let errBeginning = errMsg(props, propName, componentName, '. Expected an Element `type`'); if (typeof props[propName] !== 'function') { if (React.isValidElement(props[propName])) { return new Error(errBeginning + ', not an actual Element'); } if (typeof props[propName] !== 'string') { return new Error(errBeginning + ' such as a tag name or return value of React.createClass(...)'); } } } return createChainableTypeChecker(validate); } export default CustomPropTypes;
docs/app/Examples/collections/Table/States/TableExampleActive.js
mohammed88/Semantic-UI-React
import React from 'react' import { Table } from 'semantic-ui-react' const TableExampleActive = () => { return ( <Table celled> <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>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>Requires call</Table.Cell> </Table.Row> <Table.Row active> <Table.Cell>John</Table.Cell> <Table.Cell>Selected</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 active>Jill</Table.Cell> <Table.Cell>Approved</Table.Cell> <Table.Cell>None</Table.Cell> </Table.Row> </Table.Body> </Table> ) } export default TableExampleActive
src/components/screens/highScoreScreen/index.js
jiriKuba/Calculatic
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { View, Text, StyleSheet } from 'react-native'; import * as actions from '../../../containers/highScoreScreen/actions'; import HighScoreHistory from '../../highScoreHistory/'; import MenuButton from '../../menuButton/'; class HighScoreScreen extends Component { render() { const { onMainScreen, highScores, lastScore } = this.props; return ( <View style={styles.container}> <View style={styles.rowContainer}> <MenuButton onPress={onMainScreen} /> <View style={styles.container}> <Text style={styles.header}>High Score</Text> </View> {/*margin*/} <View style={styles.container}> <Text style={styles.header}></Text> </View> </View> <View style={styles.rowContainer}> <Text style={styles.score}>{`Last score: ${lastScore ? lastScore : 0}`}</Text> </View> <View style={styles.historyContainer}> <Text style={styles.records}>{'Records'}</Text> <HighScoreHistory highScores={highScores} /> </View> </View> ); } }; HighScoreScreen.propTypes = { onMainScreen: PropTypes.func.isRequired, highScores: PropTypes.array.isRequired, lastScore: PropTypes.number, }; const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', alignItems: 'center', }, rowContainer: { flex: .1, flexDirection: 'row', justifyContent: 'center', }, historyContainer: { flex: .8, flexDirection: 'column', justifyContent: 'center', }, header: { flex: 1, fontWeight: 'bold', fontSize: 24, }, score: { fontSize: 20, }, records: { fontSize: 20, fontWeight: 'bold', textAlign: 'center', }, }); const mapStateToProps = function (state) { const { highScoreScreenReducer } = state; return { highScores: highScoreScreenReducer.highScores, lastScore: highScoreScreenReducer.lastScore, } }; function mapDispatchToProps(dispatch) { return bindActionCreators(actions, dispatch); }; export default connect(mapStateToProps, mapDispatchToProps)(HighScoreScreen);
src/client.js
lordakshaya/pages
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import createHistory from 'history/lib/createBrowserHistory'; import useScroll from 'scroll-behavior/lib/useStandardScroll'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import io from 'socket.io-client'; import {Provider} from 'react-redux'; import {reduxReactRouter, ReduxRouter} from 'redux-router'; import getRoutes from './routes'; import makeRouteHooksSafe from './helpers/makeRouteHooksSafe'; const client = new ApiClient(); // Three different types of scroll behavior available. // Documented here: https://github.com/rackt/scroll-behavior const scrollableHistory = useScroll(createHistory); const dest = document.getElementById('content'); const store = createStore(reduxReactRouter, makeRouteHooksSafe(getRoutes), scrollableHistory, client, window.__data); function initSocket() { const socket = io('', {path: '/api/ws', transports: ['polling']}); socket.on('news', (data) => { console.log(data); socket.emit('my other event', { my: 'data from client' }); }); socket.on('msg', (data) => { console.log(data); }); return socket; } global.socket = initSocket(); const component = ( <ReduxRouter routes={getRoutes(store)} /> ); ReactDOM.render( <Provider store={store} key="provider"> {component} </Provider>, dest ); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } } if (__DEVTOOLS__ && !window.devToolsExtension) { const DevTools = require('./containers/DevTools/DevTools'); ReactDOM.render( <Provider store={store} key="provider"> <div> {component} <DevTools /> </div> </Provider>, dest ); }
ajax/libs/forerunnerdb/1.3.31/fdb-core+persist.min.js
menuka94/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){{var d=a("../lib/Core");a("../lib/Persist")}"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":4,"../lib/Persist":21}],2:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Core,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),n.prototype.data=function(){return this._data},n.prototype.drop=function(){var a;if("dropped"===this._state)return!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log("Dropping collection "+this._name),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(a in this._collate)this._collate.hasOwnProperty(a)&&this.collateRemove(a);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,!0}return!1},n.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&this.primaryKey(a.primaryKey()),this.$super.apply(this,arguments)}),n.prototype.setData=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw'ForerunnerDB.Collection "'+this.name()+'": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: '+d[this._primaryKey]}else h.set(d[k],d);e=JSON.stringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.update=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';b=this.decouple(b),b=this.transformIn(b),this.debug()&&console.log('Updating some collection data for collection "'+this.name()+'"');var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},h=f.updateObject(i,e.update,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_BEFORE,d,i)!==!1?(h=f.updateObject(d,i,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_AFTER,d,i)):h=!1):h=f.updateObject(d,b,a,c,""),h};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw'ForerunnerDB.Collection "'+this.name()+'": Primary key violation in update! Key violated: '+a[this._primaryKey];return!0},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":g=!0;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":this._updateIncrement(a,p,b[p]),q=!0;break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot push to a key that is not an array! ('+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pullAll without being given an array of values to pull! ('+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! ('+p+")";var s,t,u,v,w=a[p],x=w.length,y=!0,z=d&&d.$addToSet;for(b[p].$key?(u=!1,v=new h(b[p].$key),t=v.value(b[p])[0],delete b[p].$key):z&&z.key?(u=!1,v=new h(z.key),t=v.value(b[p])[0]):(t=JSON.stringify(b[p]),u=!0),s=0;x>s;s++)if(u){if(JSON.stringify(w[s])===t){y=!1;break}}else if(t===v.value(w[s])[0]){y=!1;break}y&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+p+")";if(l=b.$index,void 0===l)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush without a $index integer value!';delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move on a key that is not an array! ('+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],"",{})){var A=b.$index;if(void 0===A)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move without a $index integer value!';delete b.$index,this._updateSpliceMove(a[p],j,A),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pop from a key that is not an array! ('+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype._updateProperty=function(a,b,c){a[b]=c,this.debug()&&console.log('ForerunnerDB.Collection: Setting non-data-bound document property "'+b+'" for collection "'+this.name()+'"')},n.prototype._updateIncrement=function(a,b,c){a[b]+=c},n.prototype._updateSpliceMove=function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Collection: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"')},n.prototype._updateSplicePush=function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},n.prototype._updatePush=function(a,b){a.push(b)},n.prototype._updatePull=function(a,b){a.splice(b,1)},n.prototype._updateMultiply=function(a,b,c){a[b]*=c},n.prototype._updateRename=function(a,b,c){a[c]=a[b],delete a[b]},n.prototype._updateOverwrite=function(a,b,c){a[b]=c},n.prototype._updateUnset=function(a,b){delete a[b]},n.prototype._updatePop=function(a,b){var c=!1;return a.length>0&&(1===b?(a.pop(),c=!0):-1===b&&(a.shift(),c=!0)),c},n.prototype.remove=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';var d,e,f,g,h,i,j,k,l=this;if(a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.deferEmit=function(){var a,b=this;this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(a=arguments,this._changeTimeout&&clearTimeout(this._changeTimeout),this._changeTimeout=setTimeout(function(){b.debug()&&console.log("ForerunnerDB.Collection: Emitting "+a[0]),b.emit.apply(b,a)},100))},n.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this[a](f)),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b()},n.prototype.insert=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f=this._deferQueue.insert,g=this._deferThreshold.insert,h=[],i=[];if(a instanceof Array){if(a.length>g)return this._deferQueue.insert=f.concat(a),void this.processQueue("insert",c);for(e=0;e<a.length;e++)d=this._insert(a[e],b+e),d===!0?h.push(a[e]):i.push({doc:a[e],reason:d})}else d=this._insert(a,b),d===!0?h.push(a):i.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),this._onInsert(h,i),c&&c(),this.deferEmit("change",{type:"insert",data:h}),{inserted:h,failed:i}},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=JSON.stringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=JSON.stringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.indexOfDocById=function(a){return this._data.indexOf(this._primaryIndex.get(a[this._primaryKey]))},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},n.prototype.subsetOf=function(){return this.__subsetOf},n.prototype._subsetOf=function(a){return this.__subsetOf=a,this},n.prototype.distinct=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=JSON.stringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C=this._metrics.create("find"),D=this.primaryKey(),E=this,F=!0,G={},H=[],I=[],J=[],K={},L=function(b){return E._match(b,a,"and",K)};if(C.start(),a){if(C.time("analyseQuery"),c=this._analyseQuery(a,b,C),C.time("analyseQuery"),C.data("analysis",c),c.hasJoin&&c.queriesJoin){for(C.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],G[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i);C.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(C.data("index.potential",c.indexMatch),C.data("index.used",c.indexMatch[0].index),C.time("indexLookup"),e=c.indexMatch[0].lookup,C.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(F=!1)):C.flag("usedIndex",!1),F&&(e&&e.length?(d=e.length,C.time("tableScan: "+d),e=e.filter(L)):(d=this._data.length,C.time("tableScan: "+d),e=this._data.filter(L)),b.$orderBy&&(C.time("sort"),e=this.sort(b.$orderBy,e),C.time("sort")),C.time("tableScan: "+d)),b.$limit&&e&&e.length>b.$limit&&(e.length=b.$limit,C.data("limit",b.$limit)),b.$decouple&&(C.time("decouple"),e=this.decouple(e),C.time("decouple"),C.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(s=k,l=this._db.collection(k),m=b.$join[f][k],t=0;t<e.length;t++){o={},p=!1,q=!1;for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$as":s=m[n];break;case"$multi":p=m[n];break;case"$require":q=m[n]}else o[n]=new h(m[n]).value(e[t])[0];r=l.find(o),!q||q&&r[0]?e[t][s]=p===!1?r[0]:r:H.push(e[t])}C.data("flag.join",!0)}if(H.length){for(C.time("removalQueue"),v=0;v<H.length;v++)u=e.indexOf(H[v]),u>-1&&e.splice(u,1);C.time("removalQueue")}if(b.$transform){for(C.time("transform"),v=0;v<e.length;v++)e.splice(v,1,b.$transform(e[v]));C.time("transform"),C.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(C.time("transformOut"),e=this.transformOut(e),C.time("transformOut")),C.data("results",e.length)}else e=[];C.time("scanFields");for(v in b)b.hasOwnProperty(v)&&0!==v.indexOf("$")&&(1===b[v]?I.push(v):0===b[v]&&J.push(v));if(C.time("scanFields"),I.length||J.length){for(C.data("flag.limitFields",!0),C.data("limitFields.on",I),C.data("limitFields.off",J),C.time("limitFields"),v=0;v<e.length;v++){B=e[v];for(w in B)B.hasOwnProperty(w)&&(I.length&&w!==D&&-1===I.indexOf(w)&&delete B[w],J.length&&J.indexOf(w)>-1&&delete B[w])}C.time("limitFields")}if(b.$elemMatch){C.data("flag.elemMatch",!0),C.time("projection-elemMatch");for(v in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length)for(x=0;x<z.length;x++)if(E._match(z[x],b.$elemMatch[v],"",{})){y.set(e[w],v,[z[x]]);break}C.time("projection-elemMatch")}if(b.$elemsMatch){C.data("flag.elemsMatch",!0),C.time("projection-elemsMatch");for(v in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length){for(A=[],x=0;x<z.length;x++)E._match(z[x],b.$elemsMatch[v],"",{})&&A.push(z[x]);y.set(e[w],v,A)}C.time("projection-elemsMatch")}return C.stop(),e.__fdbOp=C,e},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a){var b=this.find(a,{$decouple:!1})[0];return b?this._data.indexOf(b):void 0},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=c,e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f=a.shift(),g=[];if(a.length>0){b=this._sort(f,b),d=this.bucket(f.___fdbKey,b);for(e in d)d.hasOwnProperty(e)&&(c=[].concat(a),g=g.concat(this._bucketSort(c,d[e])));return g}return this._sort(f,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw'ForerunnerDB.Collection "'+this.name()+'": $orderBy clause has invalid direction: '+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d={};for(c=0;c<b.length;c++)d[b[c][a]]=d[b[c][a]]||[],d[b[c][a]].push(b[c]);return d},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),r.push("$as"in b.$join[d][e]?b.$join[d][e].$as:e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];m.subDocs.push(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.noStats?m.subDocs:(m.pathFound||(m.err="No objects found in the parent documents with a matching path of: "+b),m)},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw'ForerunnerDB.Collection "'+this.name()+'": Collection diffing requires that both collections have the same primary key!';for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"},n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({object:function(a){return this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw'ForerunnerDB.Core "'+this.name()+'": Cannot get collection '+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log("Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b).db(this),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw'ForerunnerDB.Core "'+this.name()+'": Cannot get collection with undefined name!'}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._collection)this._collection.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,count:this._collection[b].count()}):c.push({name:b,count:this._collection[b].count()}));return c},d.finishModule("Collection"),b.exports=n},{"./Crc":5,"./IndexBinaryTree":6,"./IndexHashMap":7,"./KeyValueStore":8,"./Metrics":9,"./Overload":19,"./Path":20,"./ReactorIO":22,"./Shared":23}],3:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),g=a("./Collection"),e=d.modules.Core,f=d.modules.Core.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": All collections in a collection group must have the same primary key!'}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(){if("dropped"!==this._state){var a,b,c;if(this._debug&&console.log("Dropping collection group "+this._name),this._state="dropped",this._collections&&this._collections.length)for(b=[].concat(this._collections),a=0;a<b.length;a++)this.removeCollection(b[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]);this.emit("drop",this)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":2,"./Shared":23 }],4:[function(a,b,c){"use strict";var d,e,f,g,h;d=a("./Shared"),h=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},i.prototype.moduleLoaded=new h({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Collection.js"),f=a("./Metrics.js"),g=a("./Crc.js"),i.prototype._isServer=!1,d.synthesize(i.prototype,"primaryKey"),d.synthesize(i.prototype,"state"),d.synthesize(i.prototype,"name"),i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.crc=g,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.arrayToCollection=function(a){return(new e).setData(a)},i.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},i.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},i.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},i.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d=d.concat("string"===e?c.peek(a):c.find(a)));return d},i.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},i.prototype.drop=function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this)}return!0},b.exports=i},{"./Collection.js":2,"./Crc.js":5,"./Metrics.js":9,"./Overload":19,"./Shared":23}],5:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],6:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){},g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new(f.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(f.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},g.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},g.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./Path":20,"./Shared":23}],7:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":20,"./Shared":23}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":23}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":18,"./Shared":23}],10:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],11:[function(a,b,c){"use strict";var d={chain:function(a){this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e=this._chain,f=e.length;for(d=0;f>d;d++)e[d].chainReceive(this,a,b,c)}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],12:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload");d={store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}return void 0},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=JSON.stringify(a),e=[];for(c=0;b>c;c++)e.push(JSON.parse(d));return e}return JSON.parse(JSON.stringify(a))}return void 0},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}])},b.exports=d},{"./Overload":19}],13:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],14:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d;if(this._listeners[a]["*"]){var e=this._listeners[a]["*"];for(d=e.length,c=0;d>c;c++)e[c].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&&b[0]&&b[0][this._primaryKey]){var f,g,h=this._listeners[a];for(d=b.length,c=0;d>c;c++)if(h[b[c][this._primaryKey]])for(f=h[b[c][this._primaryKey]].length,g=0;f>g;g++)h[b[c][this._primaryKey]][g].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};b.exports=e},{"./Overload":19}],15:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d){var e,f,g,h,i,j,k,l=typeof a,m=typeof b,n=!0;if(d=d||{},d.$rootQuery||(d.$rootQuery=b),"string"!==l&&"number"!==l||"string"!==m&&"number"!==m){for(k in b)if(b.hasOwnProperty(k)){if(e=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],d),i>-1)){if(i){if("or"===c)return!0}else n=i;e=!0}if(!e&&b[k]instanceof RegExp)if(e=!0,"object"==typeof a&&void 0!==a[k]&&b[k].test(a[k])){if("or"===c)return!0}else n=!1;if(!e)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],f,d)){if("or"===c)return!0}else n=!1;else if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else n=!1;else if(a&&a[k]===b[k]){if("or"===c)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else n=!1;if("and"===c&&!n)return!1}}else"number"===l?a!==b&&(n=!1):a.localeCompare(b)&&(n=!1);return n},_matchOp:function(a,b,c,d){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$or":for(var e=0;e<c.length;e++)if(this._match(b,c[e],"and",d))return!0;return!1;case"$and":for(var f=0;f<c.length;f++)if(!this._match(b,c[f],"and",d))return!1;return!0;case"$in":if(c instanceof Array){var g,h=c,i=h.length;for(g=0;i>g;g++)if(h[g]===b)return!0;return!1}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use an $in operator on a non-array key: '+a;case"$nin":if(c instanceof Array){var j,k=c,l=k.length;for(j=0;l>j;j++)if(k[j]===b)return!1;return!0}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use a $nin operator on a non-array key: '+a;case"$distinct":d.$rootQuery["//distinctLookup"]=d.$rootQuery["//distinctLookup"]||{};for(var m in c)if(c.hasOwnProperty(m))return d.$rootQuery["//distinctLookup"][m]=d.$rootQuery["//distinctLookup"][m]||{},d.$rootQuery["//distinctLookup"][m][b[m]]?!1:(d.$rootQuery["//distinctLookup"][m][b[m]]=!0,!0)}return-1}};b.exports=d},{}],16:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":19}],18:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":20,"./Shared":23}],19:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length;b++)e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),f.push(e);if(d=f.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=f.length;b>=0;b--)if(d=f.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw'ForerunnerDB.Overload "'+this.name()+'": Overloaded method does not have a matching signature for the passed arguments: '+JSON.stringify(f)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],20:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else f.push(b?{path:g,value:a[d]}:{path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":23}],21:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l=a("./Shared"),m=a("localforage");j=function(){this.init.apply(this,arguments)},j.prototype.init=function(a){a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),m.config({driver:[m.INDEXEDDB,m.WEBSQL,m.LOCALSTORAGE],name:"ForerunnerDB",storeName:"FDB"}))},l.addModule("Persist",j),l.mixin(j.prototype,"Mixin.ChainReactor"),d=l.modules.Core,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,k=l.overload,j.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},j.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":m.setDriver(m.LOCALSTORAGE);break;case"WEBSQL":m.setDriver(m.WEBSQL);break;case"INDEXEDDB":m.setDriver(m.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return m.driver()},j.prototype.save=function(a,b,c){var d;switch(d=function(a,b){a="object"==typeof a?"json::fdb::"+JSON.stringify(a):"raw::fdb::"+a,b&&b(!1,a)},this.mode()){case"localforage":d(b,function(b,d){m.setItem(a,d).then(function(a){c(!1,a)},function(a){c(a)})});break;default:c&&c("No data handler.")}},j.prototype.load=function(a,b){var c,d,e;switch(e=function(a,b){if(a){switch(c=a.split("::fdb::"),c[0]){case"json":d=JSON.parse(c[1]);break;case"raw":d=c[1]}b&&b(!1,d)}else b(!1,a)},this.mode()){case"localforage":m.getItem(a).then(function(a){e(a,b)},function(a){b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},j.prototype.drop=function(a,b){switch(this.mode()){case"localforage":m.removeItem(a).then(function(){b(!1)},function(a){b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new k({"":function(){"dropped"!==this._state&&this.drop(!0)},"function":function(a){"dropped"!==this._state&&this.drop(!0,a)},"boolean":function(a){if("dropped"!==this._state){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";if(!this._db)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when the collection is not attached to a database!";this._db.persist.drop(this._name)}f.apply(this,arguments)}},"boolean, function":function(a,b){"dropped"!==this._state&&(a&&(this._name?this._db?this._db.persist.drop(this._name,b):b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"):b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")),f.apply(this,arguments))}}),e.prototype.save=function(a){this._name?this._db?this._db.persist.save(this._name,this._data,a):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;this._name?this._db?this._db.persist.load(this._name,function(c,d){c?a&&a(c):(d&&b.setData(d),a&&a(!1))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},d.prototype.init=function(){this.persist=new j(this),i.apply(this,arguments)},d.prototype.load=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a(b):(f--,0===f&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].load(b)},d.prototype.save=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a(b):(f--,0===f&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].save(b)},l.finishModule("Persist"),b.exports=j},{"./Collection":2,"./CollectionGroup":3,"./Shared":23,localforage:31}],22:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return"dropped"!==this._state&&(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":23}],23:[function(a,b,c){"use strict";var d={version:"1.3.31",modules:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0, this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:function(a,b){var c=this.mixins[b];if(!c)throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])},synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:a("./Overload"),mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching")}};d.mixin(d,"Mixin.Events"),b.exports=d},{"./Mixin.CRUD":10,"./Mixin.ChainReactor":11,"./Mixin.Common":12,"./Mixin.Constants":13,"./Mixin.Events":14,"./Mixin.Matching":15,"./Mixin.Sorting":16,"./Mixin.Triggers":17,"./Overload":19}],24:[function(a,b,c){function d(){if(!h){h=!0;for(var a,b=g.length;b;){a=g,g=[];for(var c=-1;++c<b;)a[c]();b=g.length}h=!1}}function e(){}var f=b.exports={},g=[],h=!1;f.nextTick=function(a){g.push(a),h||setTimeout(d,0)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=e,f.addListener=e,f.once=e,f.off=e,f.removeListener=e,f.removeAllListeners=e,f.emit=e,f.binding=function(a){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(a){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},{}],25:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:27}],26:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":25,asap:27}],27:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:24}],28:[function(a,b,c){(function(){"use strict";function c(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new o(function(a,d){var e=p.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(){e.result.createObjectStore(c.storeName)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return m(d,b),d}function e(a,b){var c=this,d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=a(c.value,c.key,h++);void 0!==d?b(d):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return m(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new o(function(c,e){d.ready().then(function(){var f=d._dbInfo,g=f.db.transaction(f.storeName,"readwrite"),h=g.objectStore(f.storeName);null===b&&(b=void 0);var i=h.put(b,a);g.oncomplete=function(){void 0===b&&(b=null),c(b)},g.onabort=g.onerror=function(){e(i.error)}})["catch"](e)});return m(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(a){var b=a.target.error;"QuotaExceededError"===b&&d(b)}})["catch"](d)});return m(d,b),d}function h(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){c(g.error)}})["catch"](c)});return m(c,a),c}function i(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new o(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function m(a,b){b&&a.then(function(a){n(b,a)},function(a){b(a)})}function n(a,b){return a?setTimeout(function(){return a(null,b)},0):void 0}var o="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,p=p||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(p){var q={_driver:"asyncStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};"undefined"!=typeof b&&b.exports?b.exports=q:"function"==typeof define&&define.amd?define("asyncStorage",function(){return q}):this.asyncStorage=q}}).call(window)},{promise:26}],29:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=0;e>f;f++){var g=p.key(f),h=p.getItem(g);if(h&&(h=o.deserialize(h)),h=a(h,g.substring(d),f+1),void 0!==h)return h}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){("QuotaExceededError"===i.name||"NS_ERROR_DOM_QUOTA_REACHED"===i.name)&&f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":32,promise:26}],30:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":32,promise:26}],31:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){if(n===l.DEFINE)return void a([f],function(a){i._extend(a),c()});if(n===l.EXPORT){var k;switch(f){case i.INDEXEDDB:k=a("./drivers/indexeddb");break;case i.LOCALSTORAGE:k=a("./drivers/localstorage");break;case i.WEBSQL:k=a("./drivers/websql")}i._extend(k)}else i._extend(q[f])}else{if(!h[f])return i._driverSet=g.reject(j),void d(j);i._extend(h[f])}c()}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":28,"./drivers/localstorage":29,"./drivers/websql":30,promise:26}],32:[function(a,b,c){(function(){"use strict";function a(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,f=g;a instanceof ArrayBuffer?(d=a,f+=i):(d=a.buffer,"[object Int8Array]"===c?f+=k:"[object Uint8Array]"===c?f+=l:"[object Uint8ClampedArray]"===c?f+=m:"[object Int16Array]"===c?f+=n:"[object Uint16Array]"===c?f+=p:"[object Int32Array]"===c?f+=o:"[object Uint32Array]"===c?f+=q:"[object Float32Array]"===c?f+=r:"[object Float64Array]"===c?f+=s:b(new Error("Failed to get type for BinaryArray"))),b(f+e(d))}else if("[object Blob]"===c){var h=new FileReader;h.onload=function(){var a=e(this.result);b(g+j+a)},h.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(t){window.console.error("Couldn't convert value into a JSON string: ",a),b(null,t)}}function c(a){if(a.substring(0,h)!==g)return JSON.parse(a);var b=a.substring(t),c=a.substring(h,t),e=d(b);switch(c){case i:return e;case j:return new Blob([e]);case k:return new Int8Array(e);case l:return new Uint8Array(e);case m:return new Uint8ClampedArray(e);case n:return new Int16Array(e);case p:return new Uint16Array(e);case o:return new Int32Array(e);case q:return new Uint32Array(e);case r:return new Float32Array(e);case s:return new Float64Array(e);default:throw new Error("Unkown type: "+c)}}function d(a){var b,c,d,e,g,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=f.indexOf(a[b]),d=f.indexOf(a[b+1]),e=f.indexOf(a[b+2]),g=f.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&g;return k}function e(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=f[c[b]>>2],d+=f[(3&c[b])<<4|c[b+1]>>4],d+=f[(15&c[b+1])<<2|c[b+2]>>6],d+=f[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g="__lfsc__:",h=g.length,i="arbf",j="blob",k="si08",l="ui08",m="uic8",n="si16",o="si32",p="ur16",q="ui32",r="fl32",s="fl64",t=h+i.length,u={serialize:a,deserialize:c,stringToBuffer:d,bufferToString:e};"undefined"!=typeof b&&b.exports?b.exports=u:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return u}):this.localforageSerializer=u}).call(window)},{}]},{},[1]);
src/svg-icons/action/event-seat.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionEventSeat = (props) => ( <SvgIcon {...props}> <path d="M4 18v3h3v-3h10v3h3v-6H4zm15-8h3v3h-3zM2 10h3v3H2zm15 3H7V5c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2v8z"/> </SvgIcon> ); ActionEventSeat = pure(ActionEventSeat); ActionEventSeat.displayName = 'ActionEventSeat'; ActionEventSeat.muiName = 'SvgIcon'; export default ActionEventSeat;
ajax/libs/react-dom/16.4.0/cjs/react-dom-server.browser.production.min.js
sashberd/cdnjs
/** @license React v16.4.0 * react-dom-server.browser.production.min.js * * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';var p=require("fbjs/lib/invariant"),r=require("object-assign"),t=require("react"),w=require("fbjs/lib/emptyFunction"),x=require("fbjs/lib/emptyObject"),y=require("fbjs/lib/hyphenateStyleName"),z=require("fbjs/lib/memoizeStringOnly"); function A(a){for(var b=arguments.length-1,d="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=0;c<b;c++)d+="&args[]="+encodeURIComponent(arguments[c+1]);p(!1,"Minified React error #"+a+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",d)} var C="function"===typeof Symbol&&Symbol.for,aa=C?Symbol.for("react.portal"):60106,E=C?Symbol.for("react.fragment"):60107,ba=C?Symbol.for("react.strict_mode"):60108,ca=C?Symbol.for("react.profiler"):60114,F=C?Symbol.for("react.provider"):60109,da=C?Symbol.for("react.context"):60110,ea=C?Symbol.for("react.async_mode"):60111,fa=C?Symbol.for("react.forward_ref"):60112,ha=/^[: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][: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\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, G={},H={};function ia(a){if(H.hasOwnProperty(a))return!0;if(G.hasOwnProperty(a))return!1;if(ha.test(a))return H[a]=!0;G[a]=!0;return!1}function ja(a,b,d,c){if(null!==d&&0===d.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(c)return!1;if(null!==d)return!d.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}} function ka(a,b,d,c){if(null===b||"undefined"===typeof b||ja(a,b,d,c))return!0;if(c)return!1;if(null!==d)switch(d.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function I(a,b,d,c,k){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=c;this.attributeNamespace=k;this.mustUseProperty=d;this.propertyName=a;this.type=b}var J={}; "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){J[a]=new I(a,0,!1,a,null)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];J[b]=new I(b,1,!1,a[1],null)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){J[a]=new I(a,2,!1,a.toLowerCase(),null)}); ["autoReverse","externalResourcesRequired","preserveAlpha"].forEach(function(a){J[a]=new I(a,2,!1,a,null)});"allowFullScreen async autoFocus autoPlay controls default defer disabled formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){J[a]=new I(a,3,!1,a.toLowerCase(),null)});["checked","multiple","muted","selected"].forEach(function(a){J[a]=new I(a,3,!0,a.toLowerCase(),null)}); ["capture","download"].forEach(function(a){J[a]=new I(a,4,!1,a.toLowerCase(),null)});["cols","rows","size","span"].forEach(function(a){J[a]=new I(a,6,!1,a.toLowerCase(),null)});["rowSpan","start"].forEach(function(a){J[a]=new I(a,5,!1,a.toLowerCase(),null)});var K=/[\-:]([a-z])/g;function L(a){return a[1].toUpperCase()} "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(K, L);J[b]=new I(b,1,!1,a,null)});"xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(K,L);J[b]=new I(b,1,!1,a,"http://www.w3.org/1999/xlink")});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(K,L);J[b]=new I(b,1,!1,a,"http://www.w3.org/XML/1998/namespace")});J.tabIndex=new I("tabIndex",1,!1,"tabindex",null);var la=/["'&<>]/; function M(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=la.exec(a);if(b){var d="",c,k=0;for(c=b.index;c<a.length;c++){switch(a.charCodeAt(c)){case 34:b="&quot;";break;case 38:b="&amp;";break;case 39:b="&#x27;";break;case 60:b="&lt;";break;case 62:b="&gt;";break;default:continue}k!==c&&(d+=a.substring(k,c));k=c+1;d+=b}a=k!==c?d+a.substring(k,c):d}return a}var N={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"}; function O(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}} var P={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},ma=r({menuitem:!0},P),Q={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0, fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},na=["Webkit","ms","Moz","O"];Object.keys(Q).forEach(function(a){na.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);Q[b]=Q[a]})});var R=t.Children.toArray,S=w.thatReturns("");w.thatReturns("");var oa={listing:!0,pre:!0,textarea:!0}; function T(a){return"string"===typeof a?a:"function"===typeof a?a.displayName||a.name:null}var pa=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,U={},qa=z(function(a){return y(a)});function ra(a){var b="";t.Children.forEach(a,function(a){null==a||"string"!==typeof a&&"number"!==typeof a||(b+=a)});return b}function sa(a,b){if(a=a.contextTypes){var d={},c;for(c in a)d[c]=b[c];b=d}else b=x;return b}var ta={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null,suppressHydrationWarning:null}; function V(a,b){void 0===a&&A("152",T(b)||"Component")} function ua(a,b){function d(c,k){var d=sa(k,b),f=[],h=!1,g={isMounted:function(){return!1},enqueueForceUpdate:function(){if(null===f)return null},enqueueReplaceState:function(a,b){h=!0;f=[b]},enqueueSetState:function(a,b){if(null===f)return null;f.push(b)}},e=void 0;if(k.prototype&&k.prototype.isReactComponent){if(e=new k(c.props,d,g),"function"===typeof k.getDerivedStateFromProps){var v=k.getDerivedStateFromProps.call(null,c.props,e.state);null!=v&&(e.state=r({},e.state,v))}}else if(e=k(c.props, d,g),null==e||null==e.render){a=e;V(a,k);return}e.props=c.props;e.context=d;e.updater=g;g=e.state;void 0===g&&(e.state=g=null);if("function"===typeof e.UNSAFE_componentWillMount||"function"===typeof e.componentWillMount)if("function"===typeof e.componentWillMount&&"function"!==typeof k.getDerivedStateFromProps&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&"function"!==typeof k.getDerivedStateFromProps&&e.UNSAFE_componentWillMount(),f.length){g=f;var u=h;f=null;h=!1;if(u&& 1===g.length)e.state=g[0];else{v=u?g[0]:e.state;var m=!0;for(u=u?1:0;u<g.length;u++){var n=g[u];n="function"===typeof n?n.call(e,v,c.props,d):n;null!=n&&(m?(m=!1,v=r({},v,n)):r(v,n))}e.state=v}}else f=null;a=e.render();V(a,k);c=void 0;if("function"===typeof e.getChildContext&&(d=k.childContextTypes,"object"===typeof d)){c=e.getChildContext();for(var q in c)q in d?void 0:A("108",T(k)||"Unknown",q)}c&&(b=r({},b,c))}for(;t.isValidElement(a);){var c=a,k=c.type;if("function"!==typeof k)break;d(c,k)}return{child:a, context:b}} var W=function(){function a(b,d){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");t.isValidElement(b)?b.type!==E?b=[b]:(b=b.props.children,b=t.isValidElement(b)?[b]:R(b)):b=R(b);this.stack=[{type:null,domNamespace:N.html,children:b,childIndex:0,context:x,footer:""}];this.exhausted=!1;this.currentSelectValue=null;this.previousWasTextNode=!1;this.makeStaticMarkup=d;this.providerStack=[];this.providerIndex=-1}a.prototype.pushProvider=function(a){this.providerIndex+=1; this.providerStack[this.providerIndex]=a;a.type._context._currentValue=a.props.value};a.prototype.popProvider=function(a){this.providerStack[this.providerIndex]=null;--this.providerIndex;a=a.type._context;a._currentValue=0>this.providerIndex?a._defaultValue:this.providerStack[this.providerIndex].props.value};a.prototype.read=function(a){if(this.exhausted)return null;for(var b="";b.length<a;){if(0===this.stack.length){this.exhausted=!0;break}var c=this.stack[this.stack.length-1];if(c.childIndex>=c.children.length){var k= c.footer;b+=k;""!==k&&(this.previousWasTextNode=!1);this.stack.pop();"select"===c.type?this.currentSelectValue=null:null!=c.type&&null!=c.type.type&&c.type.type.$$typeof===F&&this.popProvider(c.type)}else k=c.children[c.childIndex++],b+=this.render(k,c.context,c.domNamespace)}return b};a.prototype.render=function(a,d,c){if("string"===typeof a||"number"===typeof a){c=""+a;if(""===c)return"";if(this.makeStaticMarkup)return M(c);if(this.previousWasTextNode)return"\x3c!-- --\x3e"+M(c);this.previousWasTextNode= !0;return M(c)}d=ua(a,d);a=d.child;d=d.context;if(null===a||!1===a)return"";if(!t.isValidElement(a)){if(null!=a&&null!=a.$$typeof){var b=a.$$typeof;b===aa?A("257"):void 0;A("258",b.toString())}a=R(a);this.stack.push({type:null,domNamespace:c,children:a,childIndex:0,context:d,footer:""});return""}b=a.type;if("string"===typeof b)return this.renderDOM(a,d,c);switch(b){case ba:case ea:case ca:case E:return a=R(a.props.children),this.stack.push({type:null,domNamespace:c,children:a,childIndex:0,context:d, footer:""}),""}if("object"===typeof b&&null!==b)switch(b.$$typeof){case fa:return a=R(b.render(a.props,a.ref)),this.stack.push({type:null,domNamespace:c,children:a,childIndex:0,context:d,footer:""}),"";case F:return b=R(a.props.children),c={type:a,domNamespace:c,children:b,childIndex:0,context:d,footer:""},this.pushProvider(a),this.stack.push(c),"";case da:return b=R(a.props.children(a.type._currentValue)),this.stack.push({type:a,domNamespace:c,children:b,childIndex:0,context:d,footer:""}),""}A("130", null==b?b:typeof b,"")};a.prototype.renderDOM=function(a,d,c){var b=a.type.toLowerCase();c===N.html&&O(b);U.hasOwnProperty(b)||(pa.test(b)?void 0:A("65",b),U[b]=!0);var f=a.props;if("input"===b)f=r({type:void 0},f,{defaultChecked:void 0,defaultValue:void 0,value:null!=f.value?f.value:f.defaultValue,checked:null!=f.checked?f.checked:f.defaultChecked});else if("textarea"===b){var h=f.value;if(null==h){h=f.defaultValue;var l=f.children;null!=l&&(null!=h?A("92"):void 0,Array.isArray(l)&&(1>=l.length? void 0:A("93"),l=l[0]),h=""+l);null==h&&(h="")}f=r({},f,{value:void 0,children:""+h})}else if("select"===b)this.currentSelectValue=null!=f.value?f.value:f.defaultValue,f=r({},f,{value:void 0});else if("option"===b){l=this.currentSelectValue;var D=ra(f.children);if(null!=l){var B=null!=f.value?f.value+"":D;h=!1;if(Array.isArray(l))for(var g=0;g<l.length;g++){if(""+l[g]===B){h=!0;break}}else h=""+l===B;f=r({selected:void 0,children:void 0},f,{selected:h,children:D})}}if(h=f)ma[b]&&(null!=h.children|| null!=h.dangerouslySetInnerHTML?A("137",b,S()):void 0),null!=h.dangerouslySetInnerHTML&&(null!=h.children?A("60"):void 0,"object"===typeof h.dangerouslySetInnerHTML&&"__html"in h.dangerouslySetInnerHTML?void 0:A("61")),null!=h.style&&"object"!==typeof h.style?A("62",S()):void 0;h=f;l=this.makeStaticMarkup;D=1===this.stack.length;B="<"+a.type;for(q in h)if(h.hasOwnProperty(q)){var e=h[q];if(null!=e){if("style"===q){g=void 0;var v="",u="";for(g in e)if(e.hasOwnProperty(g)){var m=0===g.indexOf("--"), n=e[g];null!=n&&(v+=u+qa(g)+":",u=g,m=null==n||"boolean"===typeof n||""===n?"":m||"number"!==typeof n||0===n||Q.hasOwnProperty(u)&&Q[u]?(""+n).trim():n+"px",v+=m,u=";")}e=v||null}g=null;b:if(m=b,n=h,-1===m.indexOf("-"))m="string"===typeof n.is;else switch(m){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":m=!1;break b;default:m=!0}if(m)ta.hasOwnProperty(q)||(g=q,g=ia(g)&&null!= e?g+"="+('"'+M(e)+'"'):"");else{m=q;g=e;e=J.hasOwnProperty(m)?J[m]:null;if(n="style"!==m)n=null!==e?0===e.type:!(2<m.length)||"o"!==m[0]&&"O"!==m[0]||"n"!==m[1]&&"N"!==m[1]?!1:!0;n||ka(m,g,e,!1)?g="":null!==e?(m=e.attributeName,e=e.type,g=3===e||4===e&&!0===g?m+'=""':m+"="+('"'+M(g)+'"')):g=m+"="+('"'+M(g)+'"')}g&&(B+=" "+g)}}l||D&&(B+=' data-reactroot=""');var q=B;h="";P.hasOwnProperty(b)?q+="/>":(q+=">",h="</"+a.type+">");a:{l=f.dangerouslySetInnerHTML;if(null!=l){if(null!=l.__html){l=l.__html; break a}}else if(l=f.children,"string"===typeof l||"number"===typeof l){l=M(l);break a}l=null}null!=l?(f=[],oa[b]&&"\n"===l.charAt(0)&&(q+="\n"),q+=l):f=R(f.children);a=a.type;c=null==c||"http://www.w3.org/1999/xhtml"===c?O(a):"http://www.w3.org/2000/svg"===c&&"foreignObject"===a?"http://www.w3.org/1999/xhtml":c;this.stack.push({domNamespace:c,type:b,children:f,childIndex:0,context:d,footer:h});this.previousWasTextNode=!1;return q};return a}(),X={renderToString:function(a){return(new W(a,!1)).read(Infinity)}, renderToStaticMarkup:function(a){return(new W(a,!0)).read(Infinity)},renderToNodeStream:function(){A("207")},renderToStaticNodeStream:function(){A("208")},version:"16.4.0"},Y={default:X},Z=Y&&X||Y;module.exports=Z.default?Z.default:Z;
SynapseClient/components/LoginPage.js
jmorg/synapse
import React, { Component } from 'react'; import { Image, Text, View, Navigator, Dimensions, AsyncStorage, } from 'react-native'; export class LoginPage extends Component { componentWillMount() { var navigator = this.props.navigator; var doIntroSequence = this.props.doIntroSequence; console.log("In Login page, introSequence == " + doIntroSequence); setTimeout(() => { AsyncStorage.getItem('introSequence').then((value) => { if (value !== null){ navigator.replace({ id: 'App', }); } else { AsyncStorage.setItem('introSequence', 'true'); navigator.replace({ id: 'IntroSequence', }); } }).done(); }, 2000); } render () { return ( <View style={{flex: 1, backgroundColor: '#FFFFFF', alignItems: 'center', justifyContent: 'center'}}> <Image style={{width:Dimensions.get('window').width, resizeMode:'contain'}} source={require('../images/synapselogo.png')}></Image> </View> ); } }
ajax/libs/shariff/1.3.3/shariff.min.js
SaravananRajaraman/cdnjs
/* * shariff - v1.3.2 - 25.11.2014 * https://github.com/heiseonline/shariff * Copyright (c) 2014 Ines Pauer, Philipp Busse, Sebastian Hilbig, Erich Kramer, Deniz Sesli * Licensed under the MIT <http://www.opensource.org/licenses/mit-license.php> license */ (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(e,t){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){function n(e){var t=e.length,n=it.type(e);return"function"===n||it.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function r(e,t,n){if(it.isFunction(t))return it.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return it.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(ft.test(t))return it.filter(t,e,n);t=it.filter(t,e)}return it.grep(e,function(e){return it.inArray(e,t)>=0!==n})}function i(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function o(e){var t=xt[e]={};return it.each(e.match(bt)||[],function(e,n){t[n]=!0}),t}function a(){ht.addEventListener?(ht.removeEventListener("DOMContentLoaded",s,!1),e.removeEventListener("load",s,!1)):(ht.detachEvent("onreadystatechange",s),e.detachEvent("onload",s))}function s(){(ht.addEventListener||"load"===event.type||"complete"===ht.readyState)&&(a(),it.ready())}function l(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(Et,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Nt.test(n)?it.parseJSON(n):n}catch(i){}it.data(e,t,n)}else n=void 0}return n}function u(e){var t;for(t in e)if(("data"!==t||!it.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,n,r){if(it.acceptData(e)){var i,o,a=it.expando,s=e.nodeType,l=s?it.cache:e,u=s?e[a]:e[a]&&a;if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof t)return u||(u=s?e[a]=J.pop()||it.guid++:a),l[u]||(l[u]=s?{}:{toJSON:it.noop}),("object"==typeof t||"function"==typeof t)&&(r?l[u]=it.extend(l[u],t):l[u].data=it.extend(l[u].data,t)),o=l[u],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[it.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[it.camelCase(t)])):i=o,i}}function d(e,t,n){if(it.acceptData(e)){var r,i,o=e.nodeType,a=o?it.cache:e,s=o?e[it.expando]:it.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){it.isArray(t)?t=t.concat(it.map(t,it.camelCase)):t in r?t=[t]:(t=it.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!u(r):!it.isEmptyObject(r))return}(n||(delete a[s].data,u(a[s])))&&(o?it.cleanData([e],!0):nt.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}function f(){return!0}function p(){return!1}function h(){try{return ht.activeElement}catch(e){}}function m(e){var t=Ot.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function g(e,t){var n,r,i=0,o=typeof e.getElementsByTagName!==Ct?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==Ct?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||it.nodeName(r,t)?o.push(r):it.merge(o,g(r,t));return void 0===t||t&&it.nodeName(e,t)?it.merge([e],o):o}function v(e){jt.test(e.type)&&(e.defaultChecked=e.checked)}function y(e,t){return it.nodeName(e,"table")&&it.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function b(e){return e.type=(null!==it.find.attr(e,"type"))+"/"+e.type,e}function x(e){var t=Vt.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function w(e,t){for(var n,r=0;null!=(n=e[r]);r++)it._data(n,"globalEval",!t||it._data(t[r],"globalEval"))}function T(e,t){if(1===t.nodeType&&it.hasData(e)){var n,r,i,o=it._data(e),a=it._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++)it.event.add(t,n,s[n][r])}a.data&&(a.data=it.extend({},a.data))}}function C(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!nt.noCloneEvent&&t[it.expando]){i=it._data(t);for(r in i.events)it.removeEvent(t,r,i.handle);t.removeAttribute(it.expando)}"script"===n&&t.text!==e.text?(b(t).text=e.text,x(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),nt.html5Clone&&e.innerHTML&&!it.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&jt.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 N(t,n){var r,i=it(n.createElement(t)).appendTo(n.body),o=e.getDefaultComputedStyle&&(r=e.getDefaultComputedStyle(i[0]))?r.display:it.css(i[0],"display");return i.detach(),o}function E(e){var t=ht,n=Zt[e];return n||(n=N(e,t),"none"!==n&&n||(Kt=(Kt||it("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Kt[0].contentWindow||Kt[0].contentDocument).document,t.write(),t.close(),n=N(e,t),Kt.detach()),Zt[e]=n),n}function k(e,t){return{get:function(){var n=e();if(null!=n)return n?void delete this.get:(this.get=t).apply(this,arguments)}}}function S(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=pn.length;i--;)if(t=pn[i]+n,t in e)return t;return r}function A(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=it._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&At(r)&&(o[a]=it._data(r,"olddisplay",E(r.nodeName)))):(i=At(r),(n&&"none"!==n||!i)&&it._data(r,"olddisplay",i?n:it.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 D(e,t,n){var r=un.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function j(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+=it.css(e,n+St[o],!0,i)),r?("content"===n&&(a-=it.css(e,"padding"+St[o],!0,i)),"margin"!==n&&(a-=it.css(e,"border"+St[o]+"Width",!0,i))):(a+=it.css(e,"padding"+St[o],!0,i),"padding"!==n&&(a+=it.css(e,"border"+St[o]+"Width",!0,i)));return a}function L(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=en(e),a=nt.boxSizing&&"border-box"===it.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=tn(e,t,o),(0>i||null==i)&&(i=e.style[t]),rn.test(i))return i;r=a&&(nt.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+j(e,t,n||(a?"border":"content"),r,o)+"px"}function H(e,t,n,r,i){return new H.prototype.init(e,t,n,r,i)}function _(){return setTimeout(function(){hn=void 0}),hn=it.now()}function q(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=St[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function M(e,t,n){for(var r,i=(xn[t]||[]).concat(xn["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function O(e,t,n){var r,i,o,a,s,l,u,c,d=this,f={},p=e.style,h=e.nodeType&&At(e),m=it._data(e,"fxshow");n.queue||(s=it._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,d.always(function(){d.always(function(){s.unqueued--,it.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],u=it.css(e,"display"),c="none"===u?it._data(e,"olddisplay")||E(e.nodeName):u,"inline"===c&&"none"===it.css(e,"float")&&(nt.inlineBlockNeedsLayout&&"inline"!==E(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",nt.shrinkWrapBlocks()||d.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],gn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(h?"hide":"show")){if("show"!==i||!m||void 0===m[r])continue;h=!0}f[r]=m&&m[r]||it.style(e,r)}else u=void 0;if(it.isEmptyObject(f))"inline"===("none"===u?E(e.nodeName):u)&&(p.display=u);else{m?"hidden"in m&&(h=m.hidden):m=it._data(e,"fxshow",{}),o&&(m.hidden=!h),h?it(e).show():d.done(function(){it(e).hide()}),d.done(function(){var t;it._removeData(e,"fxshow");for(t in f)it.style(e,t,f[t])});for(r in f)a=M(h?m[r]:0,r,d),r in m||(m[r]=a.start,h&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function F(e,t){var n,r,i,o,a;for(n in e)if(r=it.camelCase(n),i=t[r],o=e[n],it.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=it.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function B(e,t,n){var r,i,o=0,a=bn.length,s=it.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var t=hn||_(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:it.extend({},t),opts:it.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:hn||_(),duration:n.duration,tweens:[],createTween:function(t,n){var r=it.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(F(c,u.opts.specialEasing);a>o;o++)if(r=bn[o].call(u,e,c,u.opts))return r;return it.map(c,M,u),it.isFunction(u.opts.start)&&u.opts.start.call(e,u),it.fx.timer(it.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 P(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(bt)||[];if(it.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function R(e,t,n,r){function i(s){var l;return o[s]=!0,it.each(e[s]||[],function(e,s){var u=s(t,n,r);return"string"!=typeof u||a||o[u]?a?!(l=u):void 0:(t.dataTypes.unshift(u),i(u),!1)}),l}var o={},a=e===In;return i(t.dataTypes[0])||!o["*"]&&i("*")}function W(e,t){var n,r,i=it.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&it.extend(!0,e,n),e}function $(e,t,n){for(var r,i,o,a,s=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){l.unshift(a);break}if(l[0]in n)o=l[0];else{for(a in n){if(!l[0]||e.converters[a+" "+l[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==l[0]&&l.unshift(o),n[o]):void 0}function z(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(d){return{state:"parsererror",error:a?d:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}function I(e,t,n,r){var i;if(it.isArray(t))it.each(t,function(t,i){n||Jn.test(e)?r(e,i):I(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==it.type(t))r(e,t);else for(i in t)I(e+"["+i+"]",t[i],n,r)}function X(){try{return new e.XMLHttpRequest}catch(t){}}function U(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function V(e){return it.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var J=[],Y=J.slice,G=J.concat,Q=J.push,K=J.indexOf,Z={},et=Z.toString,tt=Z.hasOwnProperty,nt={},rt="1.11.1",it=function(e,t){return new it.fn.init(e,t)},ot=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,st=/-([\da-z])/gi,lt=function(e,t){return t.toUpperCase()};it.fn=it.prototype={jquery:rt,constructor:it,selector:"",length:0,toArray:function(){return Y.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:Y.call(this)},pushStack:function(e){var t=it.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return it.each(this,e,t)},map:function(e){return this.pushStack(it.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(Y.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Q,sort:J.sort,splice:J.splice},it.extend=it.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1;for("boolean"==typeof a&&(u=a,a=arguments[s]||{},s++),"object"==typeof a||it.isFunction(a)||(a={}),s===l&&(a=this,s--);l>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(u&&n&&(it.isPlainObject(n)||(t=it.isArray(n)))?(t?(t=!1,o=e&&it.isArray(e)?e:[]):o=e&&it.isPlainObject(e)?e:{},a[r]=it.extend(u,o,n)):void 0!==n&&(a[r]=n));return a},it.extend({expando:"jQuery"+(rt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===it.type(e)},isArray:Array.isArray||function(e){return"array"===it.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!it.isArray(e)&&e-parseFloat(e)>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==it.type(e)||e.nodeType||it.isWindow(e))return!1;try{if(e.constructor&&!tt.call(e,"constructor")&&!tt.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(nt.ownLast)for(t in e)return tt.call(e,t);for(t in e);return void 0===t||tt.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?Z[et.call(e)]||"object":typeof e},globalEval:function(t){t&&it.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(at,"ms-").replace(st,lt)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,r){var i,o=0,a=e.length,s=n(e);if(r){if(s)for(;a>o&&(i=t.apply(e[o],r),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],r),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(ot,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(n(Object(e))?it.merge(r,"string"==typeof e?[e]:e):Q.call(r,e)),r},inArray:function(e,t,n){var r;if(t){if(K)return K.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,r){var i,o=0,a=e.length,s=n(e),l=[];if(s)for(;a>o;o++)i=t(e[o],o,r),null!=i&&l.push(i);else for(o in e)i=t(e[o],o,r),null!=i&&l.push(i);return G.apply([],l)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),it.isFunction(e)?(n=Y.call(arguments,2),r=function(){return e.apply(t||this,n.concat(Y.call(arguments)))},r.guid=e.guid=e.guid||it.guid++,r):void 0},now:function(){return+new Date},support:nt}),it.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Z["[object "+t+"]"]=t.toLowerCase()});var ut=function(e){function t(e,t,n,r){var i,o,a,s,l,u,d,p,h,m;if((t?t.ownerDocument||t:R)!==H&&L(t),t=t||H,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(q&&!r){if(i=yt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&B(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return Z.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&w.getElementsByClassName&&t.getElementsByClassName)return Z.apply(n,t.getElementsByClassName(a)),n}if(w.qsa&&(!M||!M.test(e))){if(p=d=P,h=t,m=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(u=E(e),(d=t.getAttribute("id"))?p=d.replace(xt,"\\$&"):t.setAttribute("id",p),p="[id='"+p+"'] ",l=u.length;l--;)u[l]=p+f(u[l]);h=bt.test(e)&&c(t.parentNode)||t,m=u.join(",")}if(m)try{return Z.apply(n,h.querySelectorAll(m)),n}catch(g){}finally{d||t.removeAttribute("id")}}}return S(e.replace(lt,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>T.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[P]=!0,e}function i(e){var t=H.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=e.length;r--;)T.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||J)-(~e.sourceIndex||J);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&typeof e.getElementsByTagName!==V&&e}function d(){}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=$++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,l,u=[W,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(l=t[P]||(t[P]={}),(s=l[r])&&s[0]===W&&s[1]===o)return u[2]=s[2];if(l[r]=u,u[2]=e(t,n,a))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 m(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function g(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,u=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function v(e,t,n,i,o,a){return i&&!i[P]&&(i=v(i)),o&&!o[P]&&(o=v(o,a)),r(function(r,a,s,l){var u,c,d,f=[],p=[],h=a.length,v=r||m(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:g(v,f,e,s,l),b=n?o||(r?e:h||i)?[]:a:y;if(n&&n(y,b,s,l),i)for(u=g(b,p),i(u,[],s,l),c=u.length;c--;)(d=u[c])&&(b[p[c]]=!(y[p[c]]=d));if(r){if(o||e){if(o){for(u=[],c=b.length;c--;)(d=b[c])&&u.push(y[c]=d);o(null,b=[],u,l)}for(c=b.length;c--;)(d=b[c])&&(u=o?tt.call(r,d):f[c])>-1&&(r[u]=!(a[u]=d))}}else b=g(b===a?b.splice(h,b.length):b),o?o(null,a,b,l):Z.apply(a,b)})}function y(e){for(var t,n,r,i=e.length,o=T.relative[e[0].type],a=o||T.relative[" "],s=o?1:0,l=p(function(e){return e===t},a,!0),u=p(function(e){return tt.call(t,e)>-1},a,!0),c=[function(e,n,r){return!o&&(r||n!==A)||((t=n).nodeType?l(e,n,r):u(e,n,r))}];i>s;s++)if(n=T.relative[e[s].type])c=[p(h(c),n)];else{if(n=T.filter[e[s].type].apply(null,e[s].matches),n[P]){for(r=++s;i>r&&!T.relative[e[r].type];r++);return v(s>1&&h(c),s>1&&f(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(lt,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&f(e))}c.push(n)}return h(c)}function b(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,l,u){var c,d,f,p=0,h="0",m=r&&[],v=[],y=A,b=r||o&&T.find.TAG("*",u),x=W+=null==y?1:Math.random()||.1,w=b.length;for(u&&(A=a!==H&&a);h!==w&&null!=(c=b[h]);h++){if(o&&c){for(d=0;f=e[d++];)if(f(c,a,s)){l.push(c);break}u&&(W=x)}i&&((c=!f&&c)&&p--,r&&m.push(c))}if(p+=h,i&&h!==p){for(d=0;f=n[d++];)f(m,v,a,s);if(r){if(p>0)for(;h--;)m[h]||v[h]||(v[h]=Q.call(l));v=g(v)}Z.apply(l,v),u&&!r&&v.length>0&&p+n.length>1&&t.uniqueSort(l)}return u&&(W=x,A=y),m};return i?r(a):a}var x,w,T,C,N,E,k,S,A,D,j,L,H,_,q,M,O,F,B,P="sizzle"+-new Date,R=e.document,W=0,$=0,z=n(),I=n(),X=n(),U=function(e,t){return e===t&&(j=!0),0},V="undefined",J=1<<31,Y={}.hasOwnProperty,G=[],Q=G.pop,K=G.push,Z=G.push,et=G.slice,tt=G.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},nt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",rt="[\\x20\\t\\r\\n\\f]",it="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=it.replace("w","w#"),at="\\["+rt+"*("+it+")(?:"+rt+"*([*^$|!~]?=)"+rt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ot+"))|)"+rt+"*\\]",st=":("+it+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+at+")*)|.*)\\)|)",lt=new RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=new RegExp("^"+rt+"*,"+rt+"*"),ct=new RegExp("^"+rt+"*([>+~]|"+rt+")"+rt+"*"),dt=new RegExp("="+rt+"*([^\\]'\"]*?)"+rt+"*\\]","g"),ft=new RegExp(st),pt=new RegExp("^"+ot+"$"),ht={ID:new RegExp("^#("+it+")"),CLASS:new RegExp("^\\.("+it+")"),TAG:new RegExp("^("+it.replace("w","w*")+")"),ATTR:new RegExp("^"+at),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),bool:new RegExp("^(?:"+nt+")$","i"),needsContext:new RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},mt=/^(?:input|select|textarea|button)$/i,gt=/^h\d$/i,vt=/^[^{]+\{\s*\[native \w/,yt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,bt=/[+~]/,xt=/'|\\/g,wt=new RegExp("\\\\([\\da-f]{1,6}"+rt+"?|("+rt+")|.)","ig"),Tt=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{Z.apply(G=et.call(R.childNodes),R.childNodes),G[R.childNodes.length].nodeType}catch(Ct){Z={apply:G.length?function(e,t){K.apply(e,et.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}w=t.support={},N=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},L=t.setDocument=function(e){var t,n=e?e.ownerDocument||e:R,r=n.defaultView;return n!==H&&9===n.nodeType&&n.documentElement?(H=n,_=n.documentElement,q=!N(n),r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){L()},!1):r.attachEvent&&r.attachEvent("onunload",function(){L()})),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=vt.test(n.getElementsByClassName)&&i(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),w.getById=i(function(e){return _.appendChild(e).id=P,!n.getElementsByName||!n.getElementsByName(P).length}),w.getById?(T.find.ID=function(e,t){if(typeof t.getElementById!==V&&q){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},T.filter.ID=function(e){var t=e.replace(wt,Tt);return function(e){return e.getAttribute("id")===t}}):(delete T.find.ID,T.filter.ID=function(e){var t=e.replace(wt,Tt);return function(e){var n=typeof e.getAttributeNode!==V&&e.getAttributeNode("id");return n&&n.value===t}}),T.find.TAG=w.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==V?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},T.find.CLASS=w.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==V&&q?t.getElementsByClassName(e):void 0},O=[],M=[],(w.qsa=vt.test(n.querySelectorAll))&&(i(function(e){e.innerHTML="<select msallowclip=''><option selected=''></option></select>",e.querySelectorAll("[msallowclip^='']").length&&M.push("[*^$]="+rt+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||M.push("\\["+rt+"*(?:value|"+nt+")"),e.querySelectorAll(":checked").length||M.push(":checked")}),i(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&M.push("name"+rt+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),M.push(",.*:")})),(w.matchesSelector=vt.test(F=_.matches||_.webkitMatchesSelector||_.mozMatchesSelector||_.oMatchesSelector||_.msMatchesSelector))&&i(function(e){w.disconnectedMatch=F.call(e,"div"),F.call(e,"[s!='']:x"),O.push("!=",st)}),M=M.length&&new RegExp(M.join("|")),O=O.length&&new RegExp(O.join("|")),t=vt.test(_.compareDocumentPosition),B=t||vt.test(_.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return j=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r?r:(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&r||!w.sortDetached&&t.compareDocumentPosition(e)===r?e===n||e.ownerDocument===R&&B(R,e)?-1:t===n||t.ownerDocument===R&&B(R,t)?1:D?tt.call(D,e)-tt.call(D,t):0:4&r?-1:1)}:function(e,t){if(e===t)return j=!0,0;var r,i=0,o=e.parentNode,s=t.parentNode,l=[e],u=[t];if(!o||!s)return e===n?-1:t===n?1:o?-1:s?1:D?tt.call(D,e)-tt.call(D,t):0;if(o===s)return a(e,t);for(r=e;r=r.parentNode;)l.unshift(r);for(r=t;r=r.parentNode;)u.unshift(r);for(;l[i]===u[i];)i++;return i?a(l[i],u[i]):l[i]===R?-1:u[i]===R?1:0},n):H},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==H&&L(e),n=n.replace(dt,"='$1']"),!(!w.matchesSelector||!q||O&&O.test(n)||M&&M.test(n)))try{var r=F.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,H,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==H&&L(e),B(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==H&&L(e);var n=T.attrHandle[t.toLowerCase()],r=n&&Y.call(T.attrHandle,t.toLowerCase())?n(e,t,!q):void 0;return void 0!==r?r:w.attributes||!q?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(j=!w.detectDuplicates,D=!w.sortStable&&e.slice(0),e.sort(U),j){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return D=null,e},C=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=C(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=C(t);return n},T=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(wt,Tt),e[3]=(e[3]||e[4]||e[5]||"").replace(wt,Tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return ht.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&ft.test(n)&&(t=E(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(wt,Tt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=z[e+" "];return t||(t=new RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&z(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==V&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:n?(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,d,f,p,h,m=o!==a?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s;if(g){if(o){for(;m;){for(d=t;d=d[m];)if(s?d.nodeName.toLowerCase()===v:1===d.nodeType)return!1;h=m="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?g.firstChild:g.lastChild],a&&y){for(c=g[P]||(g[P]={}),u=c[e]||[],p=u[0]===W&&u[1],f=u[0]===W&&u[2],d=p&&g.childNodes[p];d=++p&&d&&d[m]||(f=p=0)||h.pop();)if(1===d.nodeType&&++f&&d===t){c[e]=[W,p,f];break}}else if(y&&(u=(t[P]||(t[P]={}))[e])&&u[0]===W)f=u[1];else for(;(d=++p&&d&&d[m]||(f=p=0)||h.pop())&&((s?d.nodeName.toLowerCase()!==v:1!==d.nodeType)||!++f||(y&&((d[P]||(d[P]={}))[e]=[W,f]),d!==t)););return f-=i,f===r||f%r===0&&f/r>=0}}},PSEUDO:function(e,n){var i,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[P]?o(n):o.length>1?(i=[e,e,"",n],T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=tt.call(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=k(e.replace(lt,"$1"));return i[P]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return function(t){return(t.textContent||t.innerText||C(t)).indexOf(e)>-1}}),lang:r(function(e){return pt.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(wt,Tt).toLowerCase(),function(t){var n;do if(n=q?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===_},focus:function(e){return e===H.activeElement&&(!H.hasFocus||H.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return gt.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"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},T.pseudos.nth=T.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})T.pseudos[x]=l(x);return d.prototype=T.filters=T.pseudos,T.setFilters=new d,E=t.tokenize=function(e,n){var r,i,o,a,s,l,u,c=I[e+" "];if(c)return n?0:c.slice(0);for(s=e,l=[],u=T.preFilter;s;){(!r||(i=ut.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),l.push(o=[])),r=!1,(i=ct.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(lt," ")}),s=s.slice(r.length));for(a in T.filter)!(i=ht[a].exec(s))||u[a]&&!(i=u[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length)); if(!r)break}return n?s.length:s?t.error(e):I(e,l).slice(0)},k=t.compile=function(e,t){var n,r=[],i=[],o=X[e+" "];if(!o){for(t||(t=E(e)),n=t.length;n--;)o=y(t[n]),o[P]?r.push(o):i.push(o);o=X(e,b(i,r)),o.selector=e}return o},S=t.select=function(e,t,n,r){var i,o,a,s,l,u="function"==typeof e&&e,d=!r&&E(e=u.selector||e);if(n=n||[],1===d.length){if(o=d[0]=d[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&q&&T.relative[o[1].type]){if(t=(T.find.ID(a.matches[0].replace(wt,Tt),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=ht.needsContext.test(e)?0:o.length;i--&&(a=o[i],!T.relative[s=a.type]);)if((l=T.find[s])&&(r=l(a.matches[0].replace(wt,Tt),bt.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return Z.apply(n,r),n;break}}return(u||k(e,d))(r,t,!q,n,bt.test(e)&&c(t.parentNode)||t),n},w.sortStable=P.split("").sort(U).join("")===P,w.detectDuplicates=!!j,L(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(H.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(nt,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(e);it.find=ut,it.expr=ut.selectors,it.expr[":"]=it.expr.pseudos,it.unique=ut.uniqueSort,it.text=ut.getText,it.isXMLDoc=ut.isXML,it.contains=ut.contains;var ct=it.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;it.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?it.find.matchesSelector(r,e)?[r]:[]:it.find.matches(e,it.grep(t,function(e){return 1===e.nodeType}))},it.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(it(e).filter(function(){for(t=0;i>t;t++)if(it.contains(r[t],this))return!0}));for(t=0;i>t;t++)it.find(e,r[t],n);return n=this.pushStack(i>1?it.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(r(this,e||[],!1))},not:function(e){return this.pushStack(r(this,e||[],!0))},is:function(e){return!!r(this,"string"==typeof e&&ct.test(e)?it(e):e||[],!1).length}});var pt,ht=e.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=it.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){if(n="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||pt).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof it?t[0]:t,it.merge(this,it.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:ht,!0)),dt.test(n[1])&&it.isPlainObject(t))for(n in t)it.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}if(r=ht.getElementById(n[2]),r&&r.parentNode){if(r.id!==n[2])return pt.find(e);this.length=1,this[0]=r}return this.context=ht,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):it.isFunction(e)?"undefined"!=typeof pt.ready?pt.ready(e):e(it):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),it.makeArray(e,this))};gt.prototype=it.fn,pt=it(ht);var vt=/^(?:parents|prev(?:Until|All))/,yt={children:!0,contents:!0,next:!0,prev:!0};it.extend({dir:function(e,t,n){for(var r=[],i=e[t];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!it(i).is(n));)1===i.nodeType&&r.push(i),i=i[t];return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),it.fn.extend({has:function(e){var t,n=it(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(it.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=ct.test(e)||"string"!=typeof e?it(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&it.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?it.unique(o):o)},index:function(e){return e?"string"==typeof e?it.inArray(this[0],it(e)):it.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(it.unique(it.merge(this.get(),it(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),it.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return it.dir(e,"parentNode")},parentsUntil:function(e,t,n){return it.dir(e,"parentNode",n)},next:function(e){return i(e,"nextSibling")},prev:function(e){return i(e,"previousSibling")},nextAll:function(e){return it.dir(e,"nextSibling")},prevAll:function(e){return it.dir(e,"previousSibling")},nextUntil:function(e,t,n){return it.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return it.dir(e,"previousSibling",n)},siblings:function(e){return it.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return it.sibling(e.firstChild)},contents:function(e){return it.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:it.merge([],e.childNodes)}},function(e,t){it.fn[e]=function(n,r){var i=it.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=it.filter(r,i)),this.length>1&&(yt[e]||(i=it.unique(i)),vt.test(e)&&(i=i.reverse())),this.pushStack(i)}});var bt=/\S+/g,xt={};it.Callbacks=function(e){e="string"==typeof e?xt[e]||o(e):it.extend({},e);var t,n,r,i,a,s,l=[],u=!e.once&&[],c=function(o){for(n=e.memory&&o,r=!0,a=s||0,s=0,i=l.length,t=!0;l&&i>a;a++)if(l[a].apply(o[0],o[1])===!1&&e.stopOnFalse){n=!1;break}t=!1,l&&(u?u.length&&c(u.shift()):n?l=[]:d.disable())},d={add:function(){if(l){var r=l.length;!function o(t){it.each(t,function(t,n){var r=it.type(n);"function"===r?e.unique&&d.has(n)||l.push(n):n&&n.length&&"string"!==r&&o(n)})}(arguments),t?i=l.length:n&&(s=r,c(n))}return this},remove:function(){return l&&it.each(arguments,function(e,n){for(var r;(r=it.inArray(n,l,r))>-1;)l.splice(r,1),t&&(i>=r&&i--,a>=r&&a--)}),this},has:function(e){return e?it.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],i=0,this},disable:function(){return l=u=n=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,n||d.disable(),this},locked:function(){return!u},fireWith:function(e,n){return!l||r&&!u||(n=n||[],n=[e,n.slice?n.slice():n],t?u.push(n):c(n)),this},fire:function(){return d.fireWith(this,arguments),this},fired:function(){return!!r}};return d},it.extend({Deferred:function(e){var t=[["resolve","done",it.Callbacks("once memory"),"resolved"],["reject","fail",it.Callbacks("once memory"),"rejected"],["notify","progress",it.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return it.Deferred(function(n){it.each(t,function(t,o){var a=it.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&it.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?it.extend(e,r):r}},i={};return r.pipe=r.then,it.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=Y.call(arguments),a=o.length,s=1!==a||e&&it.isFunction(e.promise)?a:0,l=1===s?e:it.Deferred(),u=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?Y.call(arguments):i,r===t?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&it.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,t)):--s;return s||l.resolveWith(r,o),l.promise()}});var wt;it.fn.ready=function(e){return it.ready.promise().done(e),this},it.extend({isReady:!1,readyWait:1,holdReady:function(e){e?it.readyWait++:it.ready(!0)},ready:function(e){if(e===!0?!--it.readyWait:!it.isReady){if(!ht.body)return setTimeout(it.ready);it.isReady=!0,e!==!0&&--it.readyWait>0||(wt.resolveWith(ht,[it]),it.fn.triggerHandler&&(it(ht).triggerHandler("ready"),it(ht).off("ready")))}}}),it.ready.promise=function(t){if(!wt)if(wt=it.Deferred(),"complete"===ht.readyState)setTimeout(it.ready);else if(ht.addEventListener)ht.addEventListener("DOMContentLoaded",s,!1),e.addEventListener("load",s,!1);else{ht.attachEvent("onreadystatechange",s),e.attachEvent("onload",s);var n=!1;try{n=null==e.frameElement&&ht.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!it.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}a(),it.ready()}}()}return wt.promise(t)};var Tt,Ct="undefined";for(Tt in it(nt))break;nt.ownLast="0"!==Tt,nt.inlineBlockNeedsLayout=!1,it(function(){var e,t,n,r;n=ht.getElementsByTagName("body")[0],n&&n.style&&(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ct&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",nt.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=ht.createElement("div");if(null==nt.deleteExpando){nt.deleteExpando=!0;try{delete e.test}catch(t){nt.deleteExpando=!1}}e=null}(),it.acceptData=function(e){var t=it.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t};var Nt=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Et=/([A-Z])/g;it.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?it.cache[e[it.expando]]:e[it.expando],!!e&&!u(e)},data:function(e,t,n){return c(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return c(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),it.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=it.data(o),1===o.nodeType&&!it._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=it.camelCase(r.slice(5)),l(o,r,i[r])));it._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){it.data(this,e)}):arguments.length>1?this.each(function(){it.data(this,e,t)}):o?l(o,e,it.data(o,e)):void 0},removeData:function(e){return this.each(function(){it.removeData(this,e)})}}),it.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=it._data(e,t),n&&(!r||it.isArray(n)?r=it._data(e,t,it.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=it.queue(e,t),r=n.length,i=n.shift(),o=it._queueHooks(e,t),a=function(){it.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 it._data(e,n)||it._data(e,n,{empty:it.Callbacks("once memory").add(function(){it._removeData(e,t+"queue"),it._removeData(e,n)})})}}),it.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?it.queue(this[0],e):void 0===t?this:this.each(function(){var n=it.queue(this,e,t);it._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&it.dequeue(this,e)})},dequeue:function(e){return this.each(function(){it.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=it.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=it._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var kt=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,St=["Top","Right","Bottom","Left"],At=function(e,t){return e=t||e,"none"===it.css(e,"display")||!it.contains(e.ownerDocument,e)},Dt=it.access=function(e,t,n,r,i,o,a){var s=0,l=e.length,u=null==n;if("object"===it.type(n)){i=!0;for(s in n)it.access(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,it.isFunction(r)||(a=!0),u&&(a?(t.call(e,r),t=null):(u=t,t=function(e,t,n){return u.call(it(e),n)})),t))for(;l>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:u?t.call(e):l?t(e[0],n):o},jt=/^(?:checkbox|radio)$/i;!function(){var e=ht.createElement("input"),t=ht.createElement("div"),n=ht.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",nt.leadingWhitespace=3===t.firstChild.nodeType,nt.tbody=!t.getElementsByTagName("tbody").length,nt.htmlSerialize=!!t.getElementsByTagName("link").length,nt.html5Clone="<:nav></:nav>"!==ht.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,n.appendChild(e),nt.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",nt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,n.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",nt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,nt.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){nt.noCloneEvent=!1}),t.cloneNode(!0).click()),null==nt.deleteExpando){nt.deleteExpando=!0;try{delete t.test}catch(r){nt.deleteExpando=!1}}}(),function(){var t,n,r=ht.createElement("div");for(t in{submit:!0,change:!0,focusin:!0})n="on"+t,(nt[t+"Bubbles"]=n in e)||(r.setAttribute(n,"t"),nt[t+"Bubbles"]=r.attributes[n].expando===!1);r=null}();var Lt=/^(?:input|select|textarea)$/i,Ht=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,qt=/^(?:focusinfocus|focusoutblur)$/,Mt=/^([^.]*)(?:\.(.+)|)$/;it.event={global:{},add:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=it._data(e);if(g){for(n.handler&&(l=n,n=l.handler,i=l.selector),n.guid||(n.guid=it.guid++),(a=g.events)||(a=g.events={}),(c=g.handle)||(c=g.handle=function(e){return typeof it===Ct||e&&it.event.triggered===e.type?void 0:it.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(bt)||[""],s=t.length;s--;)o=Mt.exec(t[s])||[],p=m=o[1],h=(o[2]||"").split(".").sort(),p&&(u=it.event.special[p]||{},p=(i?u.delegateType:u.bindType)||p,u=it.event.special[p]||{},d=it.extend({type:p,origType:m,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&it.expr.match.needsContext.test(i),namespace:h.join(".")},l),(f=a[p])||(f=a[p]=[],f.delegateCount=0,u.setup&&u.setup.call(e,r,h,c)!==!1||(e.addEventListener?e.addEventListener(p,c,!1):e.attachEvent&&e.attachEvent("on"+p,c))),u.add&&(u.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),i?f.splice(f.delegateCount++,0,d):f.push(d),it.event.global[p]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=it.hasData(e)&&it._data(e);if(g&&(c=g.events)){for(t=(t||"").match(bt)||[""],u=t.length;u--;)if(s=Mt.exec(t[u])||[],p=m=s[1],h=(s[2]||"").split(".").sort(),p){for(d=it.event.special[p]||{},p=(r?d.delegateType:d.bindType)||p,f=c[p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;o--;)a=f[o],!i&&m!==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--,d.remove&&d.remove.call(e,a));l&&!f.length&&(d.teardown&&d.teardown.call(e,h,g.handle)!==!1||it.removeEvent(e,p,g.handle),delete c[p])}else for(p in c)it.event.remove(e,p+t[u],n,r,!0);it.isEmptyObject(c)&&(delete g.handle,it._removeData(e,"events"))}},trigger:function(t,n,r,i){var o,a,s,l,u,c,d,f=[r||ht],p=tt.call(t,"type")?t.type:t,h=tt.call(t,"namespace")?t.namespace.split("."):[];if(s=c=r=r||ht,3!==r.nodeType&&8!==r.nodeType&&!qt.test(p+it.event.triggered)&&(p.indexOf(".")>=0&&(h=p.split("."),p=h.shift(),h.sort()),a=p.indexOf(":")<0&&"on"+p,t=t[it.expando]?t:new it.Event(p,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=h.join("."),t.namespace_re=t.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),n=null==n?[t]:it.makeArray(n,[t]),u=it.event.special[p]||{},i||!u.trigger||u.trigger.apply(r,n)!==!1)){if(!i&&!u.noBubble&&!it.isWindow(r)){for(l=u.delegateType||p,qt.test(l+p)||(s=s.parentNode);s;s=s.parentNode)f.push(s),c=s;c===(r.ownerDocument||ht)&&f.push(c.defaultView||c.parentWindow||e)}for(d=0;(s=f[d++])&&!t.isPropagationStopped();)t.type=d>1?l:u.bindType||p,o=(it._data(s,"events")||{})[t.type]&&it._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&it.acceptData(s)&&(t.result=o.apply(s,n),t.result===!1&&t.preventDefault());if(t.type=p,!i&&!t.isDefaultPrevented()&&(!u._default||u._default.apply(f.pop(),n)===!1)&&it.acceptData(r)&&a&&r[p]&&!it.isWindow(r)){c=r[a],c&&(r[a]=null),it.event.triggered=p;try{r[p]()}catch(m){}it.event.triggered=void 0,c&&(r[a]=c)}return t.result}},dispatch:function(e){e=it.event.fix(e);var t,n,r,i,o,a=[],s=Y.call(arguments),l=(it._data(this,"events")||{})[e.type]||[],u=it.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(a=it.event.handlers.call(this,e,l),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,o=0;(r=i.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,n=((it.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s),void 0!==n&&(e.result=n)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,l=e.target;if(s&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(i=[],o=0;s>o;o++)r=t[o],n=r.selector+" ",void 0===i[n]&&(i[n]=r.needsContext?it(n,this).index(l)>=0:it.find(n,this,null,[l]).length),i[n]&&i.push(r);i.length&&a.push({elem:l,handlers:i})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[it.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=_t.test(i)?this.mouseHooks:Ht.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new it.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||ht),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||ht,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==h()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===h()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return it.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return it.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=it.extend(new it.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?it.event.trigger(i,null,t):it.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},it.removeEvent=ht.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]===Ct&&(e[r]=null),e.detachEvent(r,n))},it.Event=function(e,t){return this instanceof it.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:p):this.type=e,t&&it.extend(this,t),this.timeStamp=e&&e.timeStamp||it.now(),void(this[it.expando]=!0)):new it.Event(e,t)},it.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},it.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){it.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!it.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),nt.submitBubbles||(it.event.special.submit={setup:function(){return it.nodeName(this,"form")?!1:void it.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=it.nodeName(t,"input")||it.nodeName(t,"button")?t.form:void 0;n&&!it._data(n,"submitBubbles")&&(it.event.add(n,"submit._submit",function(e){e._submit_bubble=!0}),it._data(n,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&it.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return it.nodeName(this,"form")?!1:void it.event.remove(this,"._submit")}}),nt.changeBubbles||(it.event.special.change={setup:function(){return Lt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(it.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),it.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),it.event.simulate("change",this,e,!0)})),!1):void it.event.add(this,"beforeactivate._change",function(e){var t=e.target;Lt.test(t.nodeName)&&!it._data(t,"changeBubbles")&&(it.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||it.event.simulate("change",this.parentNode,e,!0)}),it._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return it.event.remove(this,"._change"),!Lt.test(this.nodeName)}}),nt.focusinBubbles||it.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){it.event.simulate(t,e.target,it.event.fix(e),!0)};it.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=it._data(r,t);i||r.addEventListener(e,n,!0),it._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=it._data(r,t)-1;i?it._data(r,t,i):(r.removeEventListener(e,n,!0),it._removeData(r,t))}}}),it.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(o in e)this.on(o,t,n,e[o],i);return this}if(null==n&&null==r?(r=t,n=t=void 0):null==r&&("string"==typeof t?(r=n,n=void 0):(r=n,n=t,t=void 0)),r===!1)r=p;else if(!r)return this;return 1===i&&(a=r,r=function(e){return it().off(e),a.apply(this,arguments)},r.guid=a.guid||(a.guid=it.guid++)),this.each(function(){it.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,it(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=p),this.each(function(){it.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){it.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?it.event.trigger(e,t,n,!0):void 0}});var Ot="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Ft=/ jQuery\d+="(?:null|\d+)"/g,Bt=new RegExp("<(?:"+Ot+")[\\s/>]","i"),Pt=/^\s+/,Rt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Wt=/<([\w:]+)/,$t=/<tbody/i,zt=/<|&#?\w+;/,It=/<(?:script|style|link)/i,Xt=/checked\s*(?:[^=]|=\s*.checked.)/i,Ut=/^$|\/(?:java|ecma)script/i,Vt=/^true\/(.*)/,Jt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Yt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:nt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Gt=m(ht),Qt=Gt.appendChild(ht.createElement("div"));Yt.optgroup=Yt.option,Yt.tbody=Yt.tfoot=Yt.colgroup=Yt.caption=Yt.thead,Yt.th=Yt.td,it.extend({clone:function(e,t,n){var r,i,o,a,s,l=it.contains(e.ownerDocument,e);if(nt.html5Clone||it.isXMLDoc(e)||!Bt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Qt.innerHTML=e.outerHTML,Qt.removeChild(o=Qt.firstChild)),!(nt.noCloneEvent&&nt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||it.isXMLDoc(e)))for(r=g(o),s=g(e),a=0;null!=(i=s[a]);++a)r[a]&&C(i,r[a]);if(t)if(n)for(s=s||g(e),r=r||g(o),a=0;null!=(i=s[a]);a++)T(i,r[a]);else T(e,o);return r=g(o,"script"),r.length>0&&w(r,!l&&g(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){for(var i,o,a,s,l,u,c,d=e.length,f=m(t),p=[],h=0;d>h;h++)if(o=e[h],o||0===o)if("object"===it.type(o))it.merge(p,o.nodeType?[o]:o);else if(zt.test(o)){for(s=s||f.appendChild(t.createElement("div")),l=(Wt.exec(o)||["",""])[1].toLowerCase(),c=Yt[l]||Yt._default,s.innerHTML=c[1]+o.replace(Rt,"<$1></$2>")+c[2],i=c[0];i--;)s=s.lastChild;if(!nt.leadingWhitespace&&Pt.test(o)&&p.push(t.createTextNode(Pt.exec(o)[0])),!nt.tbody)for(o="table"!==l||$t.test(o)?"<table>"!==c[1]||$t.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;i--;)it.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(it.merge(p,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=f.lastChild}else p.push(t.createTextNode(o));for(s&&f.removeChild(s),nt.appendChecked||it.grep(g(p,"input"),v),h=0;o=p[h++];)if((!r||-1===it.inArray(o,r))&&(a=it.contains(o.ownerDocument,o),s=g(f.appendChild(o),"script"),a&&w(s),n))for(i=0;o=s[i++];)Ut.test(o.type||"")&&n.push(o);return s=null,f},cleanData:function(e,t){for(var n,r,i,o,a=0,s=it.expando,l=it.cache,u=nt.deleteExpando,c=it.event.special;null!=(n=e[a]);a++)if((t||it.acceptData(n))&&(i=n[s],o=i&&l[i])){if(o.events)for(r in o.events)c[r]?it.event.remove(n,r):it.removeEvent(n,r,o.handle);l[i]&&(delete l[i],u?delete n[s]:typeof n.removeAttribute!==Ct?n.removeAttribute(s):n[s]=null,J.push(i))}}}),it.fn.extend({text:function(e){return Dt(this,function(e){return void 0===e?it.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ht).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=y(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=y(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=e?it.filter(e,this):this,i=0;null!=(n=r[i]);i++)t||1!==n.nodeType||it.cleanData(g(n)),n.parentNode&&(t&&it.contains(n.ownerDocument,n)&&w(g(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&it.cleanData(g(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&it.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 it.clone(this,e,t)})},html:function(e){return Dt(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Ft,""):void 0;if(!("string"!=typeof e||It.test(e)||!nt.htmlSerialize&&Bt.test(e)||!nt.leadingWhitespace&&Pt.test(e)||Yt[(Wt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Rt,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(it.cleanData(g(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,it.cleanData(g(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=G.apply([],e);var n,r,i,o,a,s,l=0,u=this.length,c=this,d=u-1,f=e[0],p=it.isFunction(f);if(p||u>1&&"string"==typeof f&&!nt.checkClone&&Xt.test(f))return this.each(function(n){var r=c.eq(n);p&&(e[0]=f.call(this,n,r.html())),r.domManip(e,t)});if(u&&(s=it.buildFragment(e,this[0].ownerDocument,!1,this),n=s.firstChild,1===s.childNodes.length&&(s=n),n)){for(o=it.map(g(s,"script"),b),i=o.length;u>l;l++)r=s,l!==d&&(r=it.clone(r,!0,!0),i&&it.merge(o,g(r,"script"))),t.call(this[l],r,l);if(i)for(a=o[o.length-1].ownerDocument,it.map(o,x),l=0;i>l;l++)r=o[l],Ut.test(r.type||"")&&!it._data(r,"globalEval")&&it.contains(a,r)&&(r.src?it._evalUrl&&it._evalUrl(r.src):it.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Jt,"")));s=n=null}return this}}),it.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){it.fn[e]=function(e){for(var n,r=0,i=[],o=it(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),it(o[r])[t](n),Q.apply(i,n.get());return this.pushStack(i)}});var Kt,Zt={};!function(){var e;nt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;return n=ht.getElementsByTagName("body")[0],n&&n.style?(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ct&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(ht.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0}}();var en,tn,nn=/^margin/,rn=new RegExp("^("+kt+")(?!px)[a-z%]+$","i"),on=/^(top|right|bottom|left)$/;e.getComputedStyle?(en=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)},tn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||en(e),a=n?n.getPropertyValue(t)||n[t]:void 0,n&&(""!==a||it.contains(e.ownerDocument,e)||(a=it.style(e,t)),rn.test(a)&&nn.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0===a?a:a+""}):ht.documentElement.currentStyle&&(en=function(e){return e.currentStyle },tn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||en(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),rn.test(a)&&!on.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"}),function(){function t(){var t,n,r,i;n=ht.getElementsByTagName("body")[0],n&&n.style&&(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),t.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",o=a=!1,l=!0,e.getComputedStyle&&(o="1%"!==(e.getComputedStyle(t,null)||{}).top,a="4px"===(e.getComputedStyle(t,null)||{width:"4px"}).width,i=t.appendChild(ht.createElement("div")),i.style.cssText=t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",t.style.width="1px",l=!parseFloat((e.getComputedStyle(i,null)||{}).marginRight)),t.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=t.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",s=0===i[0].offsetHeight,s&&(i[0].style.display="",i[1].style.display="none",s=0===i[0].offsetHeight),n.removeChild(r))}var n,r,i,o,a,s,l;n=ht.createElement("div"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",i=n.getElementsByTagName("a")[0],r=i&&i.style,r&&(r.cssText="float:left;opacity:.5",nt.opacity="0.5"===r.opacity,nt.cssFloat=!!r.cssFloat,n.style.backgroundClip="content-box",n.cloneNode(!0).style.backgroundClip="",nt.clearCloneStyle="content-box"===n.style.backgroundClip,nt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,it.extend(nt,{reliableHiddenOffsets:function(){return null==s&&t(),s},boxSizingReliable:function(){return null==a&&t(),a},pixelPosition:function(){return null==o&&t(),o},reliableMarginRight:function(){return null==l&&t(),l}}))}(),it.swap=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};var an=/alpha\([^)]*\)/i,sn=/opacity\s*=\s*([^)]*)/,ln=/^(none|table(?!-c[ea]).+)/,un=new RegExp("^("+kt+")(.*)$","i"),cn=new RegExp("^([+-])=("+kt+")","i"),dn={position:"absolute",visibility:"hidden",display:"block"},fn={letterSpacing:"0",fontWeight:"400"},pn=["Webkit","O","Moz","ms"];it.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=tn(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":nt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=it.camelCase(t),l=e.style;if(t=it.cssProps[s]||(it.cssProps[s]=S(l,s)),a=it.cssHooks[t]||it.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];if(o=typeof n,"string"===o&&(i=cn.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(it.css(e,t)),o="number"),null!=n&&n===n&&("number"!==o||it.cssNumber[s]||(n+="px"),nt.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{l[t]=n}catch(u){}}},css:function(e,t,n,r){var i,o,a,s=it.camelCase(t);return t=it.cssProps[s]||(it.cssProps[s]=S(e.style,s)),a=it.cssHooks[t]||it.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=tn(e,t,r)),"normal"===o&&t in fn&&(o=fn[t]),""===n||n?(i=parseFloat(o),n===!0||it.isNumeric(i)?i||0:o):o}}),it.each(["height","width"],function(e,t){it.cssHooks[t]={get:function(e,n,r){return n?ln.test(it.css(e,"display"))&&0===e.offsetWidth?it.swap(e,dn,function(){return L(e,t,r)}):L(e,t,r):void 0},set:function(e,n,r){var i=r&&en(e);return D(e,n,r?j(e,t,r,nt.boxSizing&&"border-box"===it.css(e,"boxSizing",!1,i),i):0)}}}),nt.opacity||(it.cssHooks.opacity={get:function(e,t){return sn.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=it.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===it.trim(o.replace(an,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=an.test(o)?o.replace(an,i):o+" "+i)}}),it.cssHooks.marginRight=k(nt.reliableMarginRight,function(e,t){return t?it.swap(e,{display:"inline-block"},tn,[e,"marginRight"]):void 0}),it.each({margin:"",padding:"",border:"Width"},function(e,t){it.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+St[r]+t]=o[r]||o[r-2]||o[0];return i}},nn.test(e)||(it.cssHooks[e+t].set=D)}),it.fn.extend({css:function(e,t){return Dt(this,function(e,t,n){var r,i,o={},a=0;if(it.isArray(t)){for(r=en(e),i=t.length;i>a;a++)o[t[a]]=it.css(e,t[a],!1,r);return o}return void 0!==n?it.style(e,t,n):it.css(e,t)},e,t,arguments.length>1)},show:function(){return A(this,!0)},hide:function(){return A(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){At(this)?it(this).show():it(this).hide()})}}),it.Tween=H,H.prototype={constructor:H,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||(it.cssNumber[n]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(e){var t,n=H.propHooks[this.prop];return this.pos=t=this.options.duration?it.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):H.propHooks._default.set(this),this}},H.prototype.init.prototype=H.prototype,H.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=it.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){it.fx.step[e.prop]?it.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[it.cssProps[e.prop]]||it.cssHooks[e.prop])?it.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},it.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},it.fx=H.prototype.init,it.fx.step={};var hn,mn,gn=/^(?:toggle|show|hide)$/,vn=new RegExp("^(?:([+-])=|)("+kt+")([a-z%]*)$","i"),yn=/queueHooks$/,bn=[O],xn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=vn.exec(t),o=i&&i[3]||(it.cssNumber[e]?"":"px"),a=(it.cssNumber[e]||"px"!==o&&+r)&&vn.exec(it.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,it.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}]};it.Animation=it.extend(B,{tweener:function(e,t){it.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],xn[n]=xn[n]||[],xn[n].unshift(t)},prefilter:function(e,t){t?bn.unshift(e):bn.push(e)}}),it.speed=function(e,t,n){var r=e&&"object"==typeof e?it.extend({},e):{complete:n||!n&&t||it.isFunction(e)&&e,duration:e,easing:n&&t||t&&!it.isFunction(t)&&t};return r.duration=it.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in it.fx.speeds?it.fx.speeds[r.duration]:it.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){it.isFunction(r.old)&&r.old.call(this),r.queue&&it.dequeue(this,r.queue)},r},it.fn.extend({fadeTo:function(e,t,n,r){return this.filter(At).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=it.isEmptyObject(e),o=it.speed(t,n,r),a=function(){var t=B(this,it.extend({},e),o);(i||it._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=it.timers,a=it._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&yn.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&it.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=it._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=it.timers,a=r?r.length:0;for(n.finish=!0,it.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})}}),it.each(["toggle","show","hide"],function(e,t){var n=it.fn[t];it.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(q(t,!0),e,r,i)}}),it.each({slideDown:q("show"),slideUp:q("hide"),slideToggle:q("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){it.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),it.timers=[],it.fx.tick=function(){var e,t=it.timers,n=0;for(hn=it.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||it.fx.stop(),hn=void 0},it.fx.timer=function(e){it.timers.push(e),e()?it.fx.start():it.timers.pop()},it.fx.interval=13,it.fx.start=function(){mn||(mn=setInterval(it.fx.tick,it.fx.interval))},it.fx.stop=function(){clearInterval(mn),mn=null},it.fx.speeds={slow:600,fast:200,_default:400},it.fn.delay=function(e,t){return e=it.fx?it.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e,t,n,r,i;t=ht.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],n=ht.createElement("select"),i=n.appendChild(ht.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",nt.getSetAttribute="t"!==t.className,nt.style=/top/.test(r.getAttribute("style")),nt.hrefNormalized="/a"===r.getAttribute("href"),nt.checkOn=!!e.value,nt.optSelected=i.selected,nt.enctype=!!ht.createElement("form").enctype,n.disabled=!0,nt.optDisabled=!i.disabled,e=ht.createElement("input"),e.setAttribute("value",""),nt.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),nt.radioValue="t"===e.value}();var wn=/\r/g;it.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=it.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,it(this).val()):e,null==i?i="":"number"==typeof i?i+="":it.isArray(i)&&(i=it.map(i,function(e){return null==e?"":e+""})),t=it.valHooks[this.type]||it.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return t=it.valHooks[i.type]||it.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(wn,""):null==n?"":n)}}}),it.extend({valHooks:{option:{get:function(e){var t=it.find.attr(e,"value");return null!=t?t:it.trim(it.text(e))}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(nt.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&it.nodeName(n.parentNode,"optgroup"))){if(t=it(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=it.makeArray(t),a=i.length;a--;)if(r=i[a],it.inArray(it.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),it.each(["radio","checkbox"],function(){it.valHooks[this]={set:function(e,t){return it.isArray(t)?e.checked=it.inArray(it(e).val(),t)>=0:void 0}},nt.checkOn||(it.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Tn,Cn,Nn=it.expr.attrHandle,En=/^(?:checked|selected)$/i,kn=nt.getSetAttribute,Sn=nt.input;it.fn.extend({attr:function(e,t){return Dt(this,it.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){it.removeAttr(this,e)})}}),it.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===Ct?it.prop(e,t,n):(1===o&&it.isXMLDoc(e)||(t=t.toLowerCase(),r=it.attrHooks[t]||(it.expr.match.bool.test(t)?Cn:Tn)),void 0===n?r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=it.find.attr(e,t),null==i?void 0:i):null!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):void it.removeAttr(e,t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(bt);if(o&&1===e.nodeType)for(;n=o[i++];)r=it.propFix[n]||n,it.expr.match.bool.test(n)?Sn&&kn||!En.test(n)?e[r]=!1:e[it.camelCase("default-"+n)]=e[r]=!1:it.attr(e,n,""),e.removeAttribute(kn?n:r)},attrHooks:{type:{set:function(e,t){if(!nt.radioValue&&"radio"===t&&it.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),Cn={set:function(e,t,n){return t===!1?it.removeAttr(e,n):Sn&&kn||!En.test(n)?e.setAttribute(!kn&&it.propFix[n]||n,n):e[it.camelCase("default-"+n)]=e[n]=!0,n}},it.each(it.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Nn[t]||it.find.attr;Nn[t]=Sn&&kn||!En.test(t)?function(e,t,r){var i,o;return r||(o=Nn[t],Nn[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,Nn[t]=o),i}:function(e,t,n){return n?void 0:e[it.camelCase("default-"+t)]?t.toLowerCase():null}}),Sn&&kn||(it.attrHooks.value={set:function(e,t,n){return it.nodeName(e,"input")?void(e.defaultValue=t):Tn&&Tn.set(e,t,n)}}),kn||(Tn={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},Nn.id=Nn.name=Nn.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},it.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Tn.set},it.attrHooks.contenteditable={set:function(e,t,n){Tn.set(e,""===t?!1:t,n)}},it.each(["width","height"],function(e,t){it.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),nt.style||(it.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var An=/^(?:input|select|textarea|button|object)$/i,Dn=/^(?:a|area)$/i;it.fn.extend({prop:function(e,t){return Dt(this,it.prop,e,t,arguments.length>1)},removeProp:function(e){return e=it.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),it.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!it.isXMLDoc(e),o&&(t=it.propFix[t]||t,i=it.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=it.find.attr(e,"tabindex");return t?parseInt(t,10):An.test(e.nodeName)||Dn.test(e.nodeName)&&e.href?0:-1}}}}),nt.hrefNormalized||it.each(["href","src"],function(e,t){it.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),nt.optSelected||(it.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),it.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){it.propFix[this.toLowerCase()]=this}),nt.enctype||(it.propFix.enctype="encoding");var jn=/[\t\r\n\f]/g;it.fn.extend({addClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u="string"==typeof e&&e;if(it.isFunction(e))return this.each(function(t){it(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(bt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(jn," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=it.trim(r),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(it.isFunction(e))return this.each(function(t){it(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(bt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(jn," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=e?it.trim(r):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):this.each(it.isFunction(e)?function(n){it(this).toggleClass(e.call(this,n,this.className,t),t)}:function(){if("string"===n)for(var t,r=0,i=it(this),o=e.match(bt)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else(n===Ct||"boolean"===n)&&(this.className&&it._data(this,"__className__",this.className),this.className=this.className||e===!1?"":it._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(jn," ").indexOf(t)>=0)return!0;return!1}}),it.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){it.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),it.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 Ln=it.now(),Hn=/\?/,_n=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;it.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=it.trim(t+"");return i&&!it.trim(i.replace(_n,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():it.error("Invalid JSON: "+t)},it.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{e.DOMParser?(r=new DOMParser,n=r.parseFromString(t,"text/xml")):(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t))}catch(i){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||it.error("Invalid XML: "+t),n};var qn,Mn,On=/#.*$/,Fn=/([?&])_=[^&]*/,Bn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Pn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Rn=/^(?:GET|HEAD)$/,Wn=/^\/\//,$n=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,zn={},In={},Xn="*/".concat("*");try{Mn=location.href}catch(Un){Mn=ht.createElement("a"),Mn.href="",Mn=Mn.href}qn=$n.exec(Mn.toLowerCase())||[],it.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Mn,type:"GET",isLocal:Pn.test(qn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Xn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":it.parseJSON,"text xml":it.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?W(W(e,it.ajaxSettings),t):W(it.ajaxSettings,e)},ajaxPrefilter:P(zn),ajaxTransport:P(In),ajax:function(e,t){function n(e,t,n,r){var i,c,v,y,x,T=t;2!==b&&(b=2,s&&clearTimeout(s),u=void 0,a=r||"",w.readyState=e>0?4:0,i=e>=200&&300>e||304===e,n&&(y=$(d,w,n)),y=z(d,y,w,i),i?(d.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(it.lastModified[o]=x),x=w.getResponseHeader("etag"),x&&(it.etag[o]=x)),204===e||"HEAD"===d.type?T="nocontent":304===e?T="notmodified":(T=y.state,c=y.data,v=y.error,i=!v)):(v=T,(e||!T)&&(T="error",0>e&&(e=0))),w.status=e,w.statusText=(t||T)+"",i?h.resolveWith(f,[c,T,w]):h.rejectWith(f,[w,T,v]),w.statusCode(g),g=void 0,l&&p.trigger(i?"ajaxSuccess":"ajaxError",[w,d,i?c:v]),m.fireWith(f,[w,T]),l&&(p.trigger("ajaxComplete",[w,d]),--it.active||it.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,l,u,c,d=it.ajaxSetup({},t),f=d.context||d,p=d.context&&(f.nodeType||f.jquery)?it(f):it.event,h=it.Deferred(),m=it.Callbacks("once memory"),g=d.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c)for(c={};t=Bn.exec(a);)c[t[1].toLowerCase()]=t[2];t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=y[n]=y[n]||e,v[e]=t),this},overrideMimeType:function(e){return b||(d.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)g[t]=[g[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||x;return u&&u.abort(t),n(0,t),this}};if(h.promise(w).complete=m.add,w.success=w.done,w.error=w.fail,d.url=((e||d.url||Mn)+"").replace(On,"").replace(Wn,qn[1]+"//"),d.type=t.method||t.type||d.method||d.type,d.dataTypes=it.trim(d.dataType||"*").toLowerCase().match(bt)||[""],null==d.crossDomain&&(r=$n.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]===qn[1]&&r[2]===qn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(qn[3]||("http:"===qn[1]?"80":"443")))),d.data&&d.processData&&"string"!=typeof d.data&&(d.data=it.param(d.data,d.traditional)),R(zn,d,t,w),2===b)return w;l=d.global,l&&0===it.active++&&it.event.trigger("ajaxStart"),d.type=d.type.toUpperCase(),d.hasContent=!Rn.test(d.type),o=d.url,d.hasContent||(d.data&&(o=d.url+=(Hn.test(o)?"&":"?")+d.data,delete d.data),d.cache===!1&&(d.url=Fn.test(o)?o.replace(Fn,"$1_="+Ln++):o+(Hn.test(o)?"&":"?")+"_="+Ln++)),d.ifModified&&(it.lastModified[o]&&w.setRequestHeader("If-Modified-Since",it.lastModified[o]),it.etag[o]&&w.setRequestHeader("If-None-Match",it.etag[o])),(d.data&&d.hasContent&&d.contentType!==!1||t.contentType)&&w.setRequestHeader("Content-Type",d.contentType),w.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+("*"!==d.dataTypes[0]?", "+Xn+"; q=0.01":""):d.accepts["*"]);for(i in d.headers)w.setRequestHeader(i,d.headers[i]);if(d.beforeSend&&(d.beforeSend.call(f,w,d)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](d[i]);if(u=R(In,d,t,w)){w.readyState=1,l&&p.trigger("ajaxSend",[w,d]),d.async&&d.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},d.timeout));try{b=1,u.send(v,n)}catch(T){if(!(2>b))throw T;n(-1,T)}}else n(-1,"No Transport");return w},getJSON:function(e,t,n){return it.get(e,t,n,"json")},getScript:function(e,t){return it.get(e,void 0,t,"script")}}),it.each(["get","post"],function(e,t){it[t]=function(e,n,r,i){return it.isFunction(n)&&(i=i||r,r=n,n=void 0),it.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),it.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){it.fn[t]=function(e){return this.on(t,e)}}),it._evalUrl=function(e){return it.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},it.fn.extend({wrapAll:function(e){if(it.isFunction(e))return this.each(function(t){it(this).wrapAll(e.call(this,t))});if(this[0]){var t=it(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(it.isFunction(e)?function(t){it(this).wrapInner(e.call(this,t))}:function(){var t=it(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=it.isFunction(e);return this.each(function(n){it(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){it.nodeName(this,"body")||it(this).replaceWith(this.childNodes)}).end()}}),it.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!nt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||it.css(e,"display"))},it.expr.filters.visible=function(e){return!it.expr.filters.hidden(e)};var Vn=/%20/g,Jn=/\[\]$/,Yn=/\r?\n/g,Gn=/^(?:submit|button|image|reset|file)$/i,Qn=/^(?:input|select|textarea|keygen)/i;it.param=function(e,t){var n,r=[],i=function(e,t){t=it.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=it.ajaxSettings&&it.ajaxSettings.traditional),it.isArray(e)||e.jquery&&!it.isPlainObject(e))it.each(e,function(){i(this.name,this.value)});else for(n in e)I(n,e[n],t,i);return r.join("&").replace(Vn,"+")},it.fn.extend({serialize:function(){return it.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=it.prop(this,"elements");return e?it.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!it(this).is(":disabled")&&Qn.test(this.nodeName)&&!Gn.test(e)&&(this.checked||!jt.test(e))}).map(function(e,t){var n=it(this).val();return null==n?null:it.isArray(n)?it.map(n,function(e){return{name:t.name,value:e.replace(Yn,"\r\n")}}):{name:t.name,value:n.replace(Yn,"\r\n")}}).get()}}),it.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||U()}:X;var Kn=0,Zn={},er=it.ajaxSettings.xhr();e.ActiveXObject&&it(e).on("unload",function(){for(var e in Zn)Zn[e](void 0,!0)}),nt.cors=!!er&&"withCredentials"in er,er=nt.ajax=!!er,er&&it.ajaxTransport(function(e){if(!e.crossDomain||nt.cors){var t;return{send:function(n,r){var i,o=e.xhr(),a=++Kn;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(e.hasContent&&e.data||null),t=function(n,i){var s,l,u;if(t&&(i||4===o.readyState))if(delete Zn[a],t=void 0,o.onreadystatechange=it.noop,i)4!==o.readyState&&o.abort();else{u={},s=o.status,"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(c){l=""}s||!e.isLocal||e.crossDomain?1223===s&&(s=204):s=u.text?200:404}u&&r(s,l,u,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Zn[a]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),it.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return it.globalEval(e),e}}}),it.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),it.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=ht.head||it("head")[0]||ht.documentElement;return{send:function(r,i){t=ht.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],nr=/(=)\?(?=&|$)|\?\?/;it.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||it.expando+"_"+Ln++;return this[e]=!0,e}}),it.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=t.jsonp!==!1&&(nr.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&nr.test(t.data)&&"data");return s||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=it.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(nr,"$1"+i):t.jsonp!==!1&&(t.url+=(Hn.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||it.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,tr.push(i)),a&&it.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),it.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||ht;var r=dt.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=it.buildFragment([e],t,i),i&&i.length&&it(i).remove(),it.merge([],r.childNodes))};var rr=it.fn.load;it.fn.load=function(e,t,n){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>=0&&(r=it.trim(e.slice(s,e.length)),e=e.slice(0,s)),it.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),a.length>0&&it.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){i=arguments,a.html(r?it("<div>").append(it.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){a.each(n,i||[e.responseText,t,e])}),this},it.expr.filters.animated=function(e){return it.grep(it.timers,function(t){return e===t.elem}).length};var ir=e.document.documentElement;it.offset={setOffset:function(e,t,n){var r,i,o,a,s,l,u,c=it.css(e,"position"),d=it(e),f={};"static"===c&&(e.style.position="relative"),s=d.offset(),o=it.css(e,"top"),l=it.css(e,"left"),u=("absolute"===c||"fixed"===c)&&it.inArray("auto",[o,l])>-1,u?(r=d.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(l)||0),it.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):d.css(f)}},it.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){it.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o)return t=o.documentElement,it.contains(t,i)?(typeof i.getBoundingClientRect!==Ct&&(r=i.getBoundingClientRect()),n=V(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===it.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),it.nodeName(e[0],"html")||(n=e.offset()),n.top+=it.css(e[0],"borderTopWidth",!0),n.left+=it.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-it.css(r,"marginTop",!0),left:t.left-n.left-it.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||ir;e&&!it.nodeName(e,"html")&&"static"===it.css(e,"position");)e=e.offsetParent;return e||ir})}}),it.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);it.fn[e]=function(r){return Dt(this,function(e,r,i){var o=V(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?it(o).scrollLeft():i,n?i:it(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),it.each(["top","left"],function(e,t){it.cssHooks[t]=k(nt.pixelPosition,function(e,n){return n?(n=tn(e,t),rn.test(n)?it(e).position()[t]+"px":n):void 0})}),it.each({Height:"height",Width:"width"},function(e,t){it.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){it.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return Dt(this,function(t,n,r){var i;return it.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?it.css(t,n,a):it.style(t,n,r,a) },t,o?r:void 0,o,null)}})}),it.fn.size=function(){return this.length},it.fn.andSelf=it.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return it});var or=e.jQuery,ar=e.$;return it.noConflict=function(t){return e.$===it&&(e.$=ar),t&&e.jQuery===it&&(e.jQuery=or),it},typeof t===Ct&&(e.jQuery=e.$=it),it}); },{}],2:[function(require,module,exports){ "use strict";module.exports=function(e){var r=encodeURIComponent(e.getURL());return{popup:!0,shareText:{de:"teilen",en:"share"},name:"facebook",title:{de:"Bei Facebook teilen",en:"Share on Facebook"},shareUrl:"https://www.facebook.com/sharer/sharer.php?u="+r+e.getReferrerTrack()}}; },{}],3:[function(require,module,exports){ "use strict";module.exports=function(e){return{popup:!0,shareText:"+1",name:"googleplus",title:{de:"Bei Google+ teilen",en:"Share on Google+"},shareUrl:"https://plus.google.com/share?url="+e.getURL()+e.getReferrerTrack()}}; },{}],4:[function(require,module,exports){ "use strict";module.exports=function(e){return{popup:!1,shareText:"Info",name:"info",title:{de:"weitere Informationen",en:"more information"},shareUrl:e.getInfoUrl()}}; },{}],5:[function(require,module,exports){ "use strict";module.exports=function(e){return{popup:!1,shareText:"mail",name:"mail",title:{de:"Per E-Mail versenden",en:"Send by email"},shareUrl:e.getURL()+"?view=mail"}}; },{}],6:[function(require,module,exports){ "use strict";var $=require("jquery");module.exports=function(e){var t=function(e,t){var r=decodeURIComponent(e);if(r.length<=t)return e;var n=r.substring(0,t-1).lastIndexOf(" ");return r=encodeURIComponent(r.substring(0,n))+"…"},r=function(){var r=e.getMeta("DC.title"),n=e.getMeta("DC.creator");return r.length>0&&n.length>0?r+=" - "+n:r=$("title").text(),encodeURIComponent(t(r,120))};return{popup:!0,shareText:"tweet",name:"twitter",title:{de:"Bei Twitter teilen",en:"Share on Twitter"},shareUrl:"https://twitter.com/intent/tweet?text="+r()+"&url="+e.getURL()+e.getReferrerTrack()}}; },{"jquery":1}],7:[function(require,module,exports){ (function (global){ "use strict";var $=require("jquery"),_Shariff=function(t,e){var r=this;this.element=t,this.options=$.extend({},this.defaults,e,$(t).data());var n=[require("./services/facebook"),require("./services/googleplus"),require("./services/twitter"),require("./services/mail"),require("./services/info")];this.services=$.map(this.options.services,function(t){var e;return n.forEach(function(n){return n=n(r),n.name===t?(e=n,null):void 0}),e}),this._addButtonList(),null!==this.options.backendUrl&&this.getShares().then($.proxy(this._updateCounts,this))};_Shariff.prototype={defaults:{theme:"color",backendUrl:null,infoUrl:"http://www.heise.de/ct/artikel/2-Klicks-fuer-mehr-Datenschutz-1333879.html",lang:"de",orientation:"horizontal",referrerTrack:null,services:["twitter","facebook","googleplus","info"],url:function(){var t=global.document.location.href,e=$("link[rel=canonical]").attr("href")||this.getMeta("og:url")||"";return e.length>0&&(e.indexOf("http")<0&&(e=global.document.location.protocol+"//"+global.document.location.host+e),t=e),t}},$socialshareElement:function(){return $(this.element)},getLocalized:function(t,e){return"object"==typeof t[e]?t[e][this.options.lang]:"string"==typeof t[e]?t[e]:void 0},getMeta:function(t){var e=$('meta[name="'+t+'"],[property="'+t+'"]').attr("content");return e||""},getInfoUrl:function(){return this.options.infoUrl},getURL:function(){var t=this.options.url;return"function"==typeof t?$.proxy(t,this)():t},getReferrerTrack:function(){return this.options.referrerTrack||""},getShares:function(){return $.getJSON(this.options.backendUrl+"?url="+encodeURIComponent(this.getURL()))},_updateCounts:function(t){var e=this;$.each(t,function(t,r){r>=1e3&&(r=Math.round(r/1e3)+"k"),$(e.element).find("."+t+" a").append('<span class="share_count">'+r)})},_addButtonList:function(){var t=this,e=this.$socialshareElement(),r="theme-"+this.options.theme,n="orientation-"+this.options.orientation,i=$("<ul>").addClass(r).addClass(n);this.services.forEach(function(e){var r=$('<li class="button">').addClass(e.name),n='<span class="share_text">'+t.getLocalized(e,"shareText"),o=$("<a>").attr("href",e.shareUrl).append(n);e.popup&&o.attr("rel","popup"),o.attr("title",t.getLocalized(e,"title")),r.append(o),i.append(r)}),i.on("click",'[rel="popup"]',function(t){t.preventDefault();var e=$(this).attr("href"),r=$(this).attr("title"),n="600",i="460",o="width="+n+",height="+i;global.window.open(e,r,o)}),e.append(i)}},module.exports=_Shariff,$(".shariff").each(function(){this.shariff=new _Shariff(this)}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./services/facebook":2,"./services/googleplus":3,"./services/info":4,"./services/mail":5,"./services/twitter":6,"jquery":1}]},{},[7]);
src/components/app.js
dertnius/React.Beginner
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <div>React simple starter</div> ); } }
ajax/libs/react-native-web/0.17.4/cjs/exports/NativeEventEmitter/index.min.js
cdnjs/cdnjs
"use strict";exports.__esModule=!0,exports.default=void 0;var _NativeEventEmitter=_interopRequireDefault(require("../../vendor/react-native/NativeEventEmitter"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}var _default=_NativeEventEmitter.default;exports.default=_default,module.exports=exports.default;
ajax/libs/forerunnerdb/1.3.597/fdb-core+persist.js
iwdmb/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), Persist = _dereq_('../lib/Persist'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Persist":28,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":6,"../lib/Shim.IE8":34}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":27,"./Shared":33}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Crc, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, joinMatchData, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self._resolveDynamicQuery(joinMatchData.$query, resultArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatchData, resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; case '2d': index = new Index2d(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":7,"./Index2d":10,"./IndexBinaryTree":11,"./IndexHashMap":12,"./KeyValueStore":13,"./Metrics":14,"./Overload":26,"./Path":27,"./ReactorIO":31,"./Shared":33}],5:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":4,"./Shared":33}],6:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":8,"./Metrics.js":14,"./Overload":26,"./Shared":33}],7:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],8:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":14,"./Overload":26,"./Shared":33}],9:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],10:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":3,"./GeoHash":9,"./Path":27,"./Shared":33}],11:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":3,"./Path":27,"./Shared":33}],12:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":27,"./Shared":33}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":33}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":25,"./Shared":33}],15:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],16:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, data, options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],17:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":26,"./Serialiser":32}],18:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],19:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":26}],20:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],21:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],22:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":26}],24:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":27,"./Shared":33}],26:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],27:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":33}],28:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the auto flag which determines if the persistence module * will automatically load data for collections the first time they are * accessed and save data whenever it changes. This is disabled by * default. * @param {Boolean} val Set to true to enable, false to disable * @returns {*} */ Shared.synthesize(Persist.prototype, 'auto', function (val) { var self = this; if (val !== undefined) { if (val) { // Hook db events this._db.on('create', function () { self._autoLoad.apply(self, arguments); }); this._db.on('change', function () { self._autoSave.apply(self, arguments); }); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save enabled'); } } else { // Un-hook db events this._db.off('create', this._autoLoad); this._db.off('change', this._autoSave); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save disbled'); } } } return this.$super.call(this, val); }); Persist.prototype._autoLoad = function (obj, objType, name) { var self = this; if (typeof obj.load === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name); } obj.load(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic load failed:', err); } self.emit('load', err, data); }); } else { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping'); } } }; Persist.prototype._autoSave = function (obj, objType, name) { var self = this; if (typeof obj.save === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name); } obj.save(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic save failed:', err); } self.emit('save', err, data); }); } }; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.INDEXEDDB); break; default: throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!'); } return this; } return localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) { if (callback) { callback(err, data, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); //self.setData(data); } // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":29,"./PersistCrypto":30,"./Shared":33,"async":35,"localforage":71}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":33,"pako":72}],30:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":33,"crypto-js":44}],31:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":33}],32:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Handler for Date() objects this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); // Handler for RegExp() objects this.registerEncoder('$regexp', function (data) { if (data instanceof RegExp) { return { source: data.source, params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '') }; } }); this.registerDecoder('$regexp', function (data) { var type = typeof data; if (type === 'object') { return new RegExp(data.source, data.params); } else if (type === 'string') { return new RegExp(data); } }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],33:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.597', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":15,"./Mixin.ChainReactor":16,"./Mixin.Common":17,"./Mixin.Constants":18,"./Mixin.Events":19,"./Mixin.Matching":20,"./Mixin.Sorting":21,"./Mixin.Tags":22,"./Mixin.Triggers":23,"./Mixin.Updating":24,"./Overload":26}],34:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],35:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (!callback) { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has inexistant dependency'); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback(null); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (!q.paused && workers < q.concurrency && q.tasks.length) { while(workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":70}],36:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],37:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":38}],38:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],39:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":38}],40:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":38}],41:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":38,"./hmac":43,"./sha1":62}],42:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":37,"./core":38}],43:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":38}],44:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":36,"./cipher-core":37,"./core":38,"./enc-base64":39,"./enc-utf16":40,"./evpkdf":41,"./format-hex":42,"./hmac":43,"./lib-typedarrays":45,"./md5":46,"./mode-cfb":47,"./mode-ctr":49,"./mode-ctr-gladman":48,"./mode-ecb":50,"./mode-ofb":51,"./pad-ansix923":52,"./pad-iso10126":53,"./pad-iso97971":54,"./pad-nopadding":55,"./pad-zeropadding":56,"./pbkdf2":57,"./rabbit":59,"./rabbit-legacy":58,"./rc4":60,"./ripemd160":61,"./sha1":62,"./sha224":63,"./sha256":64,"./sha3":65,"./sha384":66,"./sha512":67,"./tripledes":68,"./x64-core":69}],45:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":38}],46:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":38}],47:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":37,"./core":38}],48:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby jhruby.web@gmail.com */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":37,"./core":38}],49:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":37,"./core":38}],50:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":37,"./core":38}],51:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":37,"./core":38}],52:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":37,"./core":38}],53:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":37,"./core":38}],54:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":37,"./core":38}],55:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":37,"./core":38}],56:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":37,"./core":38}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":38,"./hmac":43,"./sha1":62}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],59:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],60:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],61:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":38}],62:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":38}],63:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":38,"./sha256":64}],64:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":38}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":38,"./x64-core":69}],66:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":38,"./sha512":67,"./x64-core":69}],67:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":38,"./x64-core":69}],68:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; // Permuted Choice 2 constants var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],69:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":38}],70:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],71:[function(_dereq_,module,exports){ (function (process,global){ /*! localForage -- Offline Storage, Improved Version 1.3.0 https://mozilla.github.io/localForage (c) 2013-2015 Mozilla, Apache License 2.0 */ (function() { var define, requireModule, _dereq_, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = _dereq_ = 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("promise/all", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; /** Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The return promise is fulfilled with an array that gives all the values in the order they were passed in the `promises` array argument. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP @param {Array} promises @param {String} label @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ function all(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to all.'); } return new Promise(function(resolve, reject) { var results = [], remaining = promises.length, promise; if (remaining === 0) { resolve([]); } function resolver(index) { return function(value) { resolveAll(index, value); }; } function resolveAll(index, value) { results[index] = value; if (--remaining === 0) { resolve(results); } } for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && isFunction(promise.then)) { promise.then(resolver(i), reject); } else { resolveAll(i, promise); } } }); } __exports__.all = all; }); define("promise/asap", ["exports"], function(__exports__) { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this); // node function useNextTick() { return function() { process.nextTick(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } function useSetTimeout() { return function() { local.setTimeout(flush, 1); }; } var queue = []; function flush() { for (var i = 0; i < queue.length; i++) { var tuple = queue[i]; var callback = tuple[0], arg = tuple[1]; callback(arg); } queue = []; } var scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { // If length is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. scheduleFlush(); } } __exports__.asap = asap; }); define("promise/config", ["exports"], function(__exports__) { "use strict"; var config = { instrument: false }; function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } __exports__.config = config; __exports__.configure = configure; }); define("promise/polyfill", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*global self*/ var RSVPPromise = __dependency1__.Promise; var isFunction = __dependency2__.isFunction; function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = RSVPPromise; } } __exports__.polyfill = polyfill; }); define("promise/promise", ["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) { "use strict"; var config = __dependency1__.config; var configure = __dependency1__.configure; var objectOrFunction = __dependency2__.objectOrFunction; var isFunction = __dependency2__.isFunction; var now = __dependency2__.now; var all = __dependency3__.all; var race = __dependency4__.race; var staticResolve = __dependency5__.resolve; var staticReject = __dependency6__.reject; var asap = __dependency7__.asap; var counter = 0; config.async = asap; // default async is asap; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { constructor: Promise, _state: undefined, _detail: undefined, _subscribers: undefined, then: function(onFulfillment, onRejection) { var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } return thenPromise; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = all; Promise.race = race; Promise.resolve = staticResolve; Promise.reject = staticReject; function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { publish(promise, promise._state = REJECTED); } __exports__.Promise = Promise; }); define("promise/race", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; /** `RSVP.race` allows you to watch a series of promises and act as soon as the first promise given to the `promises` argument fulfills or rejects. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise that becomes fulfilled with the value the first completed promises is resolved with if the first completed promise was fulfilled, or rejected with the reason that the first completed promise was rejected with. */ function race(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to race.'); } return new Promise(function(resolve, reject) { var results = [], promise; for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); } __exports__.race = race; }); define("promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.reject` returns a promise that will become rejected with the passed `reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @for RSVP @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Promise = this; return new Promise(function (resolve, reject) { reject(reason); }); } __exports__.reject = reject; }); define("promise/resolve", ["exports"], function(__exports__) { "use strict"; function resolve(value) { /*jshint validthis:true */ if (value && typeof value === 'object' && value.constructor === this) { return value; } var Promise = this; return new Promise(function(resolve) { resolve(value); }); } __exports__.resolve = resolve; }); define("promise/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return isFunction(x) || (typeof x === "object" && x !== null); } function isFunction(x) { return typeof x === "function"; } function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.objectOrFunction = objectOrFunction; __exports__.isFunction = isFunction; __exports__.isArray = isArray; __exports__.now = now; }); requireModule('promise/polyfill').polyfill(); }());(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["localforage"] = factory(); else root["localforage"] = 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__) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { 'use strict'; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function (self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function () { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function () { try { return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var LocalForage = (function () { function LocalForage(options) { _classCallCheck(this, LocalForage); this.INDEXEDDB = DriverType.INDEXEDDB; this.LOCALSTORAGE = DriverType.LOCALSTORAGE; this.WEBSQL = DriverType.WEBSQL; this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver); } // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof options === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function (supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); promise.then(callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var self = this; var getDriverPromise = (function () { if (isLibraryDriver(driverName)) { switch (driverName) { case self.INDEXEDDB: return new Promise(function (resolve, reject) { resolve(__webpack_require__(1)); }); case self.LOCALSTORAGE: return new Promise(function (resolve, reject) { resolve(__webpack_require__(2)); }); case self.WEBSQL: return new Promise(function (resolve, reject) { resolve(__webpack_require__(4)); }); } } else if (CustomDrivers[driverName]) { return Promise.resolve(CustomDrivers[driverName]); } return Promise.reject(new Error('Driver not found.')); })(); getDriverPromise.then(callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }); if (callback && typeof callback === 'function') { serializerPromise.then(function (result) { callback(result); }); } return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); promise.then(callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; })['catch'](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () { return Promise.resolve(); }) : Promise.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })['catch'](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; }); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; })(); var localForage = new LocalForage(); exports['default'] = localForage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports) { // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; var dbContexts; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({ status: xhr.status, response: xhr.response }); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function (resolve, reject) { var blob = _createBlob([''], { type: 'image/png' }); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function () { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function (e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function (res) { resolve(!!(res && res.type === 'image/png')); }, function () { resolve(false); }).then(function () { URL.revokeObjectURL(url); }); }; }; })['catch'](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Initialize a singleton container for all running localForages. if (!dbContexts) { dbContexts = {}; } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = { // Running localForages sharing a database. forages: [], // Shared database. db: null }; // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(this); // Create an array of readiness of the related localForages. var readyPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== this) { // Don't wait for itself... readyPromises.push(forage.ready()['catch'](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise.all(readyPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k in forages) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _getConnection(dbInfo, upgradeNeeded) { return new Promise(function (resolve, reject) { if (dbInfo.db) { if (upgradeNeeded) { dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = indexedDB.open.apply(indexedDB, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function () { reject(openreq.error); }; openreq.onsuccess = function () { resolve(openreq.result); }; }); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void 0) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function (blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = asyncStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; if (dbInfo.storeName !== self._defaultConfig.storeName) { dbInfo.keyPrefix += dbInfo.storeName + '/'; } self._dbInfo = dbInfo; return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = localStorageWrapper; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; (function () { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; exports['default'] = localforageSerializer; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function () { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = webSQLStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ } /******/ ]) }); ; }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":70}],72:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":73,"./lib/inflate":74,"./lib/utils/common":75,"./lib/zlib/constants":78}],73:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ var Deflate = function(options) { this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } }; /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function(status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate alrorythm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":75,"./utils/strings":76,"./zlib/deflate.js":80,"./zlib/messages":85,"./zlib/zstream":87}],74:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var gzheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ var Inflate = function(options) { this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new gzheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); }; /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function(status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":75,"./utils/strings":76,"./zlib/constants":78,"./zlib/gzheader":81,"./zlib/inflate.js":83,"./zlib/messages":85,"./zlib/zstream":87}],75:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs+len), dest_offs); return; } // Fallback to ordinary array for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i=0, l=chunks.length; i<l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i=0, l=chunks.length; i<l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],76:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q=0; q<256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i=0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function(buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function(str) { var buf = new utils.Buf8(str.length); for (var i=0, len=buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i<len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":75}],77:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],78:[function(_dereq_,module,exports){ module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],79:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n =0; n < 256; n++) { c = n; for (var k =0; k < 8; k++) { c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],80:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only (s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH-1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length-1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH-1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ var Config = function (good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; }; var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":75,"./adler32":77,"./crc32":79,"./messages":85,"./trees":86}],81:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],82:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],83:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function ZSWAP32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window,src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = ZSWAP32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = {bits: state.lenbits}; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = {bits: state.lenbits}; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = {bits: state.distbits}; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":75,"./adler32":77,"./crc32":79,"./inffast":82,"./inftrees":84}],84:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i=0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":75}],85:[function(_dereq_,module,exports){ 'use strict'; module.exports = { '2': 'need dictionary', /* Z_NEED_DICT 2 */ '1': 'stream end', /* Z_STREAM_END 1 */ '0': '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],86:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES+2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; }; var static_l_desc; var static_d_desc; var static_bl_desc; var TreeDesc = function(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ }; function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short (s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max+1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n*2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n-base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m*2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; tree[m*2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n*2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n*2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n*2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n*2 + 1]/*.Len*/ = 5; static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n*2; var _m2 = m*2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n*2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node*2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6*2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10*2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138*2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3*(max_blindex+1) + 5+5+4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len+3+7) >>> 3; static_lenb = (s.static_len+3+7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc*2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":75}],87:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}]},{},[1]);
cerberus-dashboard/src/components/Banner/Banner.js
Nike-Inc/cerberus
/* * Copyright (c) 2020 Nike, 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. */ import React from 'react'; import { Component } from 'react'; import parse from 'html-react-parser'; import './Banner.scss'; export default class Banner extends Component { render() { const { message } = this.props; return ( <div id='banner'> {parse(message)} </div> ) } }
packages/my-joy-instances/src/components/create-instance/__tests__/affinity.spec.js
geek/joyent-portal
import React from 'react'; import renderer from 'react-test-renderer'; import 'jest-styled-components'; import { Rule, Header } from '../affinity'; import Theme from '@mocks/theme'; it('renders <Rule/> without throwing', () => { expect( renderer .create( <Theme> <Rule /> </Theme> ) .toJSON() ).toMatchSnapshot(); }); it('renders <Rule/> without throwing', () => { expect( renderer .create( <Theme> <Rule rule={{ conditional: 'must', placement: 'same', pattern: 'equalling', value: 'test', key: '', type: 'name' }} /> </Theme> ) .toJSON() ).toMatchSnapshot(); }); it('renders <Header /> without throwing', () => { expect( renderer .create( <Theme> <Header rule={{ conditional: 'must', placement: 'same', pattern: 'equalling', value: 'test', key: '', type: 'name' }} /> </Theme> ) .toJSON() ).toMatchSnapshot(); }); it('renders <Header tag/> without throwing', () => { expect( renderer .create( <Theme> <Header rule={{ conditional: 'must', placement: 'same', pattern: 'equalling', value: 'one', key: 'two', type: 'tag' }} /> </Theme> ) .toJSON() ).toMatchSnapshot(); });
files/rxjs/2.4.0/rx.lite.compat.js
Third9/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 }, 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(self) { if (self.isDisposed) { throw new Error(objectDisposed); } } function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `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 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)); var isObject = Rx.internals.isObject = function(value) { 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 = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[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 errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; 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) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; 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; }; } // Fix for Tessel if (!Object.prototype.propertyIsEnumerable) { Object.prototype.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // 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]; this.items[this.length] = undefined; 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 () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.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 len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @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 }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; 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; if (!shouldDispose) { var 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 () { if (!this.isDisposed) { this.isDisposed = true; var 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 && !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 && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function notSupported() { throw new Error('Not supported'); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); if (!item.isCancelled()) { !item.isCancelled() && item.invoke(); } } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } function notSupported() { throw new Error('Not supported'); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; var onGlobalPostMessage = function (event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { var notification = new Notification('E'); notification.exception = e; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.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( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, 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) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * 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); }; /** * 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); } function notImplemented() { throw new Error('Method not implemented'); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __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 setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = function(observer) { throw new Error('Not implemeneted'); } return ObservableBase; }(Observable)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * 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 () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); 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 () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : 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 () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : 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'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler || currentThreadScheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * 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) { return new FromArrayObservable(array, 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; }); }; function observableOf (scheduler, array) { return new FromArrayObservable(array, scheduler); } /** * 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 () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args); }; /** * 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) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = Rx.Scheduler.currentThread); return new AnonymousObservable(function (observer) { var keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursiveWithState(0, function (idx, self) { if (idx < len) { var key = keys[idx]; observer.onNext([key, obj[key]]); self(idx + 1); } else { observer.onCompleted(); } }); }); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @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 RangeObservable(start, count, scheduler); }; /** * 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. * @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} error 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.throwError = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(error); }); }); }; /** @deprecated use #some instead */ Observable.throwException = function () { //deprecate('throwException', 'throwError'); return Observable.throwError.apply(null, arguments); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); len--; Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var falseFactory = function () { return false; }, hasValue = arrayInitialize(len, falseFactory), hasValueAll = false, isDone = arrayInitialize(len, falseFactory), values = new Array(len); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (ex) { o.onError(ex); return; } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(len); for (var idx = 0; idx < len; 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); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * 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 () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).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 = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * 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) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * 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 = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([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.withLatestFrom = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } 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, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; 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) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * 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 args. * * @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 args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); 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 = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var 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; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } 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); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * 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 (o) { return source.subscribe(o); }, this); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * 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(typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * 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 (o) { 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) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, 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 (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(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; }); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector(self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); /*try { var result = this.selector(x, this.i++, this.source); } catch (e) { return this.observer.onError(e); } this.observer.onNext(result);*/ }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * 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.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate(x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @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.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; /** * 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 () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return new AnonymousObservable(function (observer) { function handler() { var results = arguments; if (selector) { try { results = selector(results); } catch (err) { return observer.onError(err); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } for(var results = [], i = 1, len = arguments.length; i < len; i++) { results.push(arguments[i]); } if (selector) { try { results = selector(results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation) { event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch (event.type) { case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { // Handles jq, Angular.js, Zepto, Marionette, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, function (o) { return subject.subscribe(o); }); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }, source); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { o.onError(err); return; } try { res = resultSelector.apply(null, values); } catch (ex) { o.onError(ex); return; } o.onNext(res); } if (isDone && values[1]) { o.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(o) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { o.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { o.onNext(q.shift()); } o.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue) { enableQueue == null && (enableQueue = true); __super__.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; (!this.enableQueue || this.queue.length === 0) && this.subject.onCompleted(); }, onError: function (error) { this.hasFailed = true; this.error = error; (!this.enableQueue || this.queue.length === 0) && this.subject.onError(error); }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(value); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while (this.queue.length >= numberOfItems && numberOfItems > 0) { this.subject.onNext(this.queue.shift()); numberOfItems--; } return this.queue.length !== 0 ? { numberOfItems: numberOfItems, returnValue: true } : { numberOfItems: numberOfItems, returnValue: false }; } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); var number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; try { ado.setDisposable(fixSubscriber(subscribe(ado))); } catch (e) { if (!ado.fail(e)) { throw e; } } } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __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 result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); return thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); if (result === errorObj) { return thrower(result.e); } }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); if (result === errorObj) { return thrower(result.e); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; 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(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * 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(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * 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(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), 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(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); 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.hasValue = false; this.observers = []; this.hasError = false; } 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(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 i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * 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(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 subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * 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.hasError = false; } 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(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * 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(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
actor-apps/app-web/src/app/components/modals/create-group/Form.react.js
chengjunjian/actor-platform
import _ from 'lodash'; import Immutable from 'immutable'; import keymirror from 'keymirror'; import React from 'react'; import { Styles, TextField, FlatButton } from 'material-ui'; import CreateGroupActionCreators from 'actions/CreateGroupActionCreators'; import ContactStore from 'stores/ContactStore'; import ContactItem from './ContactItem.react'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); const STEPS = keymirror({ NAME_INPUT: null, CONTACTS_SELECTION: null }); class CreateGroupForm extends React.Component { static displayName = 'CreateGroupForm' static childContextTypes = { muiTheme: React.PropTypes.object }; state = { step: STEPS.NAME_INPUT, selectedUserIds: new Immutable.Set() } getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ textField: { textColor: 'rgba(0,0,0,.87)', focusColor: '#68a3e7', backgroundColor: 'transparent', borderColor: '#68a3e7' } }); } render() { let stepForm; switch (this.state.step) { case STEPS.NAME_INPUT: stepForm = ( <form className="group-name" onSubmit={this.onNameSubmit}> <div className="modal-new__body"> <TextField className="login__form__input" floatingLabelText="Group name" fullWidth onChange={this.onNameChange} value={this.state.name}/> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Add members" secondary={true} type="submit"/> </footer> </form> ); break; case STEPS.CONTACTS_SELECTION: let contactList = _.map(ContactStore.getContacts(), (contact, i) => { return ( <ContactItem contact={contact} key={i} onToggle={this.onContactToggle}/> ); }); stepForm = ( <form className="group-members" onSubmit={this.onMembersSubmit}> <div className="count">{this.state.selectedUserIds.size} Members</div> <div className="modal-new__body"> <ul className="contacts__list"> {contactList} </ul> </div> <footer className="modal-new__footer text-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Create group" secondary={true} type="submit"/> </footer> </form> ); break; } return stepForm; } onContactToggle = (contact, isSelected) => { if (isSelected) { this.setState({selectedUserIds: this.state.selectedUserIds.add(contact.uid)}); } else { this.setState({selectedUserIds: this.state.selectedUserIds.remove(contact.uid)}); } } onNameChange = event => { event.preventDefault(); this.setState({name: event.target.value}); } onNameSubmit = event => { event.preventDefault(); if (this.state.name) { let name = this.state.name.trim(); if (name.length > 0) { this.setState({step: STEPS.CONTACTS_SELECTION}); } } } onMembersSubmit =event => { event.preventDefault(); CreateGroupActionCreators.createGroup(this.state.name, null, this.state.selectedUserIds.toJS()); } } export default CreateGroupForm;
ajax/libs/rxjs/2.5.2/rx.js
chriszarate/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // 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 bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `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 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)); var isObject = Rx.internals.isObject = function(value) { 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 = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[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 hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; 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) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; 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; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // 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]; this.items[this.length] = undefined; 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 () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.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 len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @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 }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; // Single assignment var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; SingleAssignmentDisposable.prototype.getDisposable = function () { return this.current; }; SingleAssignmentDisposable.prototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; !shouldDispose && (this.current = value); shouldDispose && value && value.dispose(); }; SingleAssignmentDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; // Multiple assignment disposable var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; SerialDisposable.prototype.getDisposable = function () { return this.current; }; SerialDisposable.prototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; SerialDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; /** * 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 && !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 && !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; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; 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; } /** Determines whether the given object is a scheduler */ Scheduler.isScheduler = function (s) { return s instanceof Scheduler; } 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, isScheduler = Scheduler.isScheduler; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(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[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](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([state, 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([state, 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([state, 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 NotSupportedError(); } period = normalizeTime(period); var s = state, 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); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle) }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { return thrower(result.e); } } } } var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; 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 (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); 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) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else if (root.attachEvent) { root.attachEvent('onmessage', onGlobalPostMessage); } else { root.onmessage = onGlobalPostMessage; } scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + currentId, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { !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), disposable = new SingleAssignmentDisposable(); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var id = localSetTimeout(function () { !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, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * 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 self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { 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) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * 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) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * 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 () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); 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 (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.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( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, 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) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(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); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * 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); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * 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(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var 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) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(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)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * 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 NotSupportedError('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); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * 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 () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; var EmptyObservable = (function(__super__) { inherits(EmptyObservable, __super__); function EmptyObservable(scheduler) { this.scheduler = scheduler; __super__.call(this); } EmptyObservable.prototype.subscribeCore = function (observer) { var sink = new EmptySink(observer, this); return sink.run(); }; function EmptySink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { state.onCompleted(); } EmptySink.prototype.run = function () { return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); }; return EmptyObservable; }(ObservableBase)); /** * 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 EmptyObservable(scheduler); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); 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 () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : 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 () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : 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'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * 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) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { return o.onError(e); } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; var NeverObservable = (function(__super__) { inherits(NeverObservable, __super__); function NeverObservable() { __super__.call(this); } NeverObservable.prototype.subscribeCore = function (observer) { return disposableEmpty; }; return NeverObservable; }(ObservableBase)); /** * 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 NeverObservable(); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * 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 () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * 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) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; var PairsObservable = (function(__super__) { inherits(PairsObservable, __super__); function PairsObservable(obj, scheduler) { this.obj = obj; this.keys = Object.keys(obj); this.scheduler = scheduler; __super__.call(this); } PairsObservable.prototype.subscribeCore = function (observer) { var sink = new PairsSink(observer, this); return sink.run(); }; return PairsObservable; }(ObservableBase)); function PairsSink(observer, parent) { this.observer = observer; this.parent = parent; } PairsSink.prototype.run = function () { var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length; function loopRecursive(i, recurse) { if (i < len) { var key = keys[i]; observer.onNext([key, obj[key]]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new PairsObservable(obj, scheduler); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @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 RangeObservable(start, count, scheduler); }; var RepeatObservable = (function(__super__) { inherits(RepeatObservable, __super__); function RepeatObservable(value, repeatCount, scheduler) { this.value = value; this.repeatCount = repeatCount == null ? -1 : repeatCount; this.scheduler = scheduler; __super__.call(this); } RepeatObservable.prototype.subscribeCore = function (observer) { var sink = new RepeatSink(observer, this); return sink.run(); }; return RepeatObservable; }(ObservableBase)); function RepeatSink(observer, parent) { this.observer = observer; this.parent = parent; } RepeatSink.prototype.run = function () { var observer = this.observer, value = this.parent.value; function loopRecursive(i, recurse) { if (i === -1 || i > 0) { observer.onNext(value); i > 0 && i--; } if (i === 0) { return observer.onCompleted(); } recurse(i); } return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * @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 new RepeatObservable(value, repeatCount, scheduler); }; var JustObservable = (function(__super__) { inherits(JustObservable, __super__); function JustObservable(value, scheduler) { this.value = value; this.scheduler = scheduler; __super__.call(this); } JustObservable.prototype.subscribeCore = function (observer) { var sink = new JustSink(observer, this); return sink.run(); }; function JustSink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { var value = state[0], observer = state[1]; observer.onNext(value); observer.onCompleted(); } JustSink.prototype.run = function () { return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); }; return JustObservable; }(ObservableBase)); /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just' or browsers <IE9. * @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 = Observable.returnValue = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new JustObservable(value, scheduler); }; var ThrowObservable = (function(__super__) { inherits(ThrowObservable, __super__); function ThrowObservable(error, scheduler) { this.error = error; this.scheduler = scheduler; __super__.call(this); } ThrowObservable.prototype.subscribeCore = function (observer) { var sink = new ThrowSink(observer, this); return sink.run(); }; function ThrowSink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { var error = state[0], observer = state[1]; observer.onError(error); } ThrowSink.prototype.run = function () { return this.parent.scheduler.scheduleWithState([this.parent.error, this.observer], scheduleItem); }; return ThrowObservable; }(ObservableBase)); /** * 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} error 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.throwError = Observable.throwException = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new ThrowObservable(error, scheduler); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.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); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * 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 () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).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 = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * 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) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * 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 = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * 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 (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([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.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } 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, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; 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) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * 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 args. * * @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 args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); 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 = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var 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; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } 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); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * 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 (o) { return source.subscribe(o); }, 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 (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * 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(typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * 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 (o) { 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) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, 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) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(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, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).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; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * 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.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; /** * 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(); }); }, source).mergeAll(); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @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.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; /** * 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(o) { return { '@@transducer/init': function() { return o; }, '@@transducer/step': function(obs, input) { return obs.onNext(input); }, '@@transducer/result': function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(o) { var xform = transducer(transformForObserver(o)); return source.subscribe( function(v) { try { xform['@@transducer/step'](o, v); } catch (e) { o.onError(e); } }, function (e) { o.onError(e); }, function() { xform['@@transducer/result'](o); } ); }, source); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __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 result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; 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(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * 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(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * 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(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), 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(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); 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.hasValue = false; this.observers = []; this.hasError = false; } 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(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 i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * 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(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 subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, 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; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
ui/node_modules/react-bootstrap/src/Col.js
bpatters/eservice
import React from 'react'; import classSet from 'classnames'; import constants from './constants'; const Col = React.createClass({ propTypes: { xs: React.PropTypes.number, sm: React.PropTypes.number, md: React.PropTypes.number, lg: React.PropTypes.number, xsOffset: React.PropTypes.number, smOffset: React.PropTypes.number, mdOffset: React.PropTypes.number, lgOffset: React.PropTypes.number, xsPush: React.PropTypes.number, smPush: React.PropTypes.number, mdPush: React.PropTypes.number, lgPush: React.PropTypes.number, xsPull: React.PropTypes.number, smPull: React.PropTypes.number, mdPull: React.PropTypes.number, lgPull: React.PropTypes.number, componentClass: React.PropTypes.node.isRequired }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; let classes = {}; Object.keys(constants.SIZES).forEach(function (key) { let size = constants.SIZES[key]; let prop = size; let classPart = size + '-'; if (this.props[prop]) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Offset'; classPart = size + '-offset-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Push'; classPart = size + '-push-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Pull'; classPart = size + '-pull-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } }, this); return ( <ComponentClass {...this.props} className={classSet(this.props.className, classes)}> {this.props.children} </ComponentClass> ); } }); export default Col;
assets/js/vendor/jquery-1.9.1.min.js
ericclemmons/ericclemmons.github.io
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
client/src/index.js
FlevianK/cp2-document-management-system
import 'babel-polyfill'; import React from 'react'; import routes from './routes'; import configureStore from './store/configureStore'; import initialState from './reducers/initialState'; import '../../node_modules/materialize-css/dist/css/materialize.min.css'; import '../../node_modules/materialize-css/dist/js/materialize.min'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, browserHistory } from 'react-router'; import { loadDocuments, createDocument, deleteDocument, updateDocument, searchDocumentsPage, loadDocument, loadDoc, searchDocuments, loadRoleDocuments, loadDocumentsPage, loadRoleDocumentsPage, loadDocList, loadUsers, createUser, deleteUser, updateUser, logoutUser, searchUsersPage, loadUsersPage, loginUser, searchUser, loadUser, loadRolesPage, loadRoles, createRole, deleteRole, searchRoles, searchRolesPage, updateRole, loadRole } from './actions'; const store = configureStore(); render( <Provider store={store}> <Router routes={routes} history={browserHistory} /> </Provider>, document.getElementById('app') );
public/js/jquery.min.js
Pablo-Merino/ZendFrameworkLearningProject
/*! 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);
packages/core/admin/ee/admin/pages/AuthPage/components/Providers/SSOProviders.js
wistityhq/strapi
import React from 'react'; import PropTypes from 'prop-types'; import { Grid, GridItem } from '@strapi/design-system/Grid'; import { Flex } from '@strapi/design-system/Flex'; import { Typography } from '@strapi/design-system/Typography'; import { Tooltip } from '@strapi/design-system/Tooltip'; import styled from 'styled-components'; import { useIntl } from 'react-intl'; import { Link } from 'react-router-dom'; const SSOButton = styled.a` width: ${136 / 16}rem; display: flex; justify-content: center; align-items: center; height: ${48 / 16}rem; border: 1px solid ${({ theme }) => theme.colors.neutral150}; border-radius: ${({ theme }) => theme.borderRadius}; text-decoration: inherit; &:link { text-decoration: none; } color: ${({ theme }) => theme.colors.neutral600}; `; const SSOProvidersWrapper = styled(Flex)` & a:not(:first-child):not(:last-child) { margin: 0 ${({ theme }) => theme.spaces[2]}; } & a:first-child { margin-right: ${({ theme }) => theme.spaces[2]}; } & a:last-child { margin-left: ${({ theme }) => theme.spaces[2]}; } `; const SSOProviderButton = ({ provider }) => { return ( <Tooltip label={provider.displayName}> <SSOButton href={`${strapi.backendURL}/admin/connect/${provider.uid}`}> {provider.icon ? ( <img src={provider.icon} aria-hidden alt="" height="32px" /> ) : ( <Typography>{provider.displayName}</Typography> )} </SSOButton> </Tooltip> ); }; SSOProviderButton.propTypes = { provider: PropTypes.shape({ icon: PropTypes.string, displayName: PropTypes.string.isRequired, uid: PropTypes.string.isRequired, }).isRequired, }; const SSOProviders = ({ providers, displayAllProviders }) => { const { formatMessage } = useIntl(); if (displayAllProviders) { return ( <Grid gap={4}> {providers.map(provider => ( <GridItem key={provider.uid} col={4}> <SSOProviderButton provider={provider} /> </GridItem> ))} </Grid> ); } if (providers.length > 2 && !displayAllProviders) { return ( <Grid gap={4}> {providers.slice(0, 2).map(provider => ( <GridItem key={provider.uid} col={4}> <SSOProviderButton provider={provider} /> </GridItem> ))} <GridItem col={4}> <Tooltip label={formatMessage({ id: 'Auth.form.button.login.providers.see-more', })} > <SSOButton as={Link} to="/auth/providers"> <span aria-hidden>•••</span> </SSOButton> </Tooltip> </GridItem> </Grid> ); } return ( <SSOProvidersWrapper justifyContent="center"> {providers.map(provider => ( <SSOProviderButton key={provider.uid} provider={provider} /> ))} </SSOProvidersWrapper> ); }; SSOProviders.defaultProps = { displayAllProviders: true, }; SSOProviders.propTypes = { providers: PropTypes.arrayOf(PropTypes.object).isRequired, displayAllProviders: PropTypes.bool, }; export default SSOProviders;
src/svg-icons/action/perm-device-information.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermDeviceInformation = (props) => ( <SvgIcon {...props}> <path d="M13 7h-2v2h2V7zm0 4h-2v6h2v-6zm4-9.99L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/> </SvgIcon> ); ActionPermDeviceInformation = pure(ActionPermDeviceInformation); ActionPermDeviceInformation.displayName = 'ActionPermDeviceInformation'; ActionPermDeviceInformation.muiName = 'SvgIcon'; export default ActionPermDeviceInformation;
client/app/components/TodoApp.js
russll/facebook-starter-kit
/** * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import AddTodoMutation from '../mutations/AddTodoMutation'; import TodoListFooter from './TodoListFooter'; import TodoTextInput from './TodoTextInput'; import React from 'react'; import Relay from 'react-relay'; class TodoApp extends React.Component { _handleTextInputSave = (text) => { Relay.Store.commitUpdate( new AddTodoMutation({text, viewer: this.props.viewer}) ); }; render() { var hasTodos = this.props.viewer.totalCount > 0; return ( <div> <section className="todoapp"> <header className="header"> <h1> todos </h1> <TodoTextInput autoFocus={true} className="new-todo" onSave={this._handleTextInputSave} placeholder="What needs to be done?" /> </header> {this.props.children} {hasTodos && <TodoListFooter todos={this.props.viewer.todos} viewer={this.props.viewer} /> } </section> <footer className="info"> <p> Double-click to edit a todo </p> <p> Created by the <a href="https://facebook.github.io/relay/"> Relay team </a> </p> <p> Part of <a href="http://todomvc.com">TodoMVC</a> </p> </footer> </div> ); } } export default Relay.createContainer(TodoApp, { fragments: { viewer: () => Relay.QL` fragment on User { totalCount, ${AddTodoMutation.getFragment('viewer')}, ${TodoListFooter.getFragment('viewer')}, } `, }, });
express-rest-api/node_modules/eslint-plugin-react/lib/util/pragma.js
thoughtbit/node-web-starter
/** * @fileoverview Utility functions for React pragma configuration * @author Yannick Croissant */ 'use strict'; var JSX_ANNOTATION_REGEX = /^\*\s*@jsx\s+([^\s]+)/; // Does not check for reserved keywords or unicode characters var JS_IDENTIFIER_REGEX = /^[_$a-zA-Z][_$a-zA-Z0-9]*$/; function getCreateClassFromContext(context) { var pragma = 'createClass'; // .eslintrc shared settings (http://eslint.org/docs/user-guide/configuring#adding-shared-settings) if (context.settings.react && context.settings.react.createClass) { pragma = context.settings.react.createClass; } if (!JS_IDENTIFIER_REGEX.test(pragma)) { throw new Error('createClass pragma ' + pragma + 'is not a valid function name'); } return pragma; } function getFromContext(context) { var pragma = 'React'; // .eslintrc shared settings (http://eslint.org/docs/user-guide/configuring#adding-shared-settings) if (context.settings.react && context.settings.react.pragma) { pragma = context.settings.react.pragma; } if (!JS_IDENTIFIER_REGEX.test(pragma)) { throw new Error('React pragma ' + pragma + 'is not a valid identifier'); } return pragma; } function getFromNode(node) { var matches = JSX_ANNOTATION_REGEX.exec(node.value); if (!matches) { return false; } return matches[1].split('.')[0]; } module.exports = { getCreateClassFromContext: getCreateClassFromContext, getFromContext: getFromContext, getFromNode: getFromNode };
dulor/assets/fullcalendar/jquery/jquery-1.8.1.min.js
lidah-khatulistiwa/sisfodataktp
/*! jQuery v@1.8.1 jquery.com | jquery.org/license */ (function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b_(a,b,c){var d=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0||d==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cA(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cv;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cA(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cA(a,c,d,e,"*",g)),h}function cB(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cC(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cD(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cL(){try{return new a.XMLHttpRequest}catch(b){}}function cM(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cU(){return setTimeout(function(){cN=b},0),cN=p.now()}function cV(a,b){p.each(b,function(b,c){var d=(cT[b]||[]).concat(cT["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cW(a,b,c){var d,e=0,f=0,g=cS.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cN||cU(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cN||cU(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cX(k,j.opts.specialEasing);for(;e<g;e++){d=cS[e].call(j,a,k,j.opts);if(d)return d}return cV(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cX(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(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 cY(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bZ(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cc(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cP.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cZ(a,b,c,d,e){return new cZ.prototype.init(a,b,c,d,e)}function c$(a,b){var c,d={height:a},e=0;b=b?1:0;for(;e<4;e+=2-b)c=bV[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function da(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.1",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o&&!o.call(" ")?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":a.toString().replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||f.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete")setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){var e=p.type(c);e==="function"&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&e!=="string"&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,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%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")===0&&(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&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 p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)d=p._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)~f.indexOf(" "+b[g]+" ")||(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},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(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m,n=(p._data(this,"events")||{})[c.type]||[],o=n.delegateCount,q=[].slice.call(arguments),r=!c.exclusive&&!c.namespace,s=p.event.special[c.type]||{},t=[];q[0]=c,c.delegateTarget=this;if(s.preDispatch&&s.preDispatch.call(this,c)===!1)return;if(o&&(!c.button||c.type!=="click"))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){h={},j=[];for(d=0;d<o;d++)k=n[d],l=k.selector,h[l]===b&&(h[l]=p(l,this).index(f)>=0),h[l]&&j.push(k);j.length&&t.push({elem:f,matches:j})}n.length>o&&t.push({elem:this,matches:n.slice(o)});for(d=0;d<t.length&&!c.isPropagationStopped();d++){i=t[d],c.currentTarget=i.elem;for(e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++){k=i.matches[e];if(r||!c.namespace&&!k.namespace||c.namespace_re&&c.namespace_re.test(k.namespace))c.data=k.data,c.handleObj=k,g=((p.event.special[k.origType]||{}).handle||k.handler).apply(i.elem,q),g!==b&&(c.result=g,g===!1&&(c.preventDefault(),c.stopPropagation()))}}return s.postDispatch&&s.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.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]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),!V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.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){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function $(a,b,c,d){c=c||[],b=b||q;var e,f,g,j,k=b.nodeType;if(k!==1&&k!==9)return[];if(!a||typeof a!="string")return c;g=h(b);if(!g&&!d)if(e=L.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&i(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return u.apply(c,t.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&X&&b.getElementsByClassName)return u.apply(c,t.call(b.getElementsByClassName(j),0)),c}return bk(a,b,c,d,g)}function _(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function ba(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bb(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bc(a,b,c,d){var e,g,h,i,j,k,l,m,n,p,r=!c&&b!==q,s=(r?"<s>":"")+a.replace(H,"$1<s>"),u=y[o][s];if(u)return d?0:t.call(u,0);j=a,k=[],m=0,n=f.preFilter,p=f.filter;while(j){if(!e||(g=I.exec(j)))g&&(j=j.slice(g[0].length),h.selector=l),k.push(h=[]),l="",r&&(j=" "+j);e=!1;if(g=J.exec(j))l+=g[0],j=j.slice(g[0].length),e=h.push({part:g.pop().replace(H," "),string:g[0],captures:g});for(i in p)(g=S[i].exec(j))&&(!n[i]||(g=n[i](g,b,c)))&&(l+=g[0],j=j.slice(g[0].length),e=h.push({part:i,string:g.shift(),captures:g}));if(!e)break}return l&&(h.selector=l),d?j.length:j?$.error(a):t.call(y(s,k),0)}function bd(a,b,e,f){var g=b.dir,h=s++;return a||(a=function(a){return a===e}),b.first?function(b){while(b=b[g])if(b.nodeType===1)return a(b)&&b}:f?function(b){while(b=b[g])if(b.nodeType===1&&a(b))return b}:function(b){var e,f=h+"."+c,i=f+"."+d;while(b=b[g])if(b.nodeType===1){if((e=b[o])===i)return b.sizset;if(typeof e=="string"&&e.indexOf(f)===0){if(b.sizset)return b}else{b[o]=i;if(a(b))return b.sizset=!0,b;b.sizset=!1}}}}function be(a,b){return a?function(c){var d=b(c);return d&&a(d===!0?c:d)}:b}function bf(a,b,c){var d,e,g=0;for(;d=a[g];g++)f.relative[d.part]?e=bd(e,f.relative[d.part],b,c):e=be(e,f.filter[d.part].apply(null,d.captures.concat(b,c)));return e}function bg(a){return function(b){var c,d=0;for(;c=a[d];d++)if(c(b))return!0;return!1}}function bh(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)$(a,b[e],c,d)}function bi(a,b,c,d,e,g){var h,i=f.setFilters[b.toLowerCase()];return i||$.error(b),(a||!(h=e))&&bh(a||"*",d,h=[],e),h.length>0?i(h,c,g):[]}function bj(a,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q,r,s=0,t=a.length,v=S.POS,w=new RegExp("^"+v.source+"(?!"+A+")","i"),x=function(){var a=1,c=arguments.length-2;for(;a<c;a++)arguments[a]===b&&(n[a]=b)};for(;s<t;s++){f=a[s],g="",m=e;for(h=0,i=f.length;h<i;h++){j=f[h],k=j.string;if(j.part==="PSEUDO"){v.exec(""),l=0;while(n=v.exec(k)){o=!0,p=v.lastIndex=n.index+n[0].length;if(p>l){g+=k.slice(l,n.index),l=p,q=[c],J.test(g)&&(m&&(q=m),m=e);if(r=O.test(g))g=g.slice(0,-5).replace(J,"$&*"),l++;n.length>1&&n[0].replace(w,x),m=bi(g,n[1],n[2],q,m,r)}g=""}}o||(g+=k),o=!1}g?J.test(g)?bh(g,m||[c],d,e):$(g,c,d,e?e.concat(m):m):u.apply(d,m)}return t===1?d:$.uniqueSort(d)}function bk(a,b,e,g,h){a=a.replace(H,"$1");var i,k,l,m,n,o,p,q,r,s,v=bc(a,b,h),w=b.nodeType;if(S.POS.test(a))return bj(v,b,e,g);if(g)i=t.call(g,0);else if(v.length===1){if((o=t.call(v[0],0)).length>2&&(p=o[0]).part==="ID"&&w===9&&!h&&f.relative[o[1].part]){b=f.find.ID(p.captures[0].replace(R,""),b,h)[0];if(!b)return e;a=a.slice(o.shift().string.length)}r=(v=N.exec(o[0].string))&&!v.index&&b.parentNode||b,q="";for(n=o.length-1;n>=0;n--){p=o[n],s=p.part,q=p.string+q;if(f.relative[s])break;if(f.order.test(s)){i=f.find[s](p.captures[0].replace(R,""),r,h);if(i==null)continue;a=a.slice(0,a.length-q.length)+q.replace(S[s],""),a||u.apply(e,t.call(i,0));break}}}if(a){k=j(a,b,h),c=k.dirruns++,i==null&&(i=f.find.TAG("*",N.test(a)&&b.parentNode||b));for(n=0;m=i[n];n++)d=k.runs++,k(m)&&e.push(m)}return e}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=a.document,r=q.documentElement,s=0,t=[].slice,u=[].push,v=function(a,b){return a[o]=b||!0,a},w=function(){var a={},b=[];return v(function(c,d){return b.push(c)>f.cacheLength&&delete a[b.shift()],a[c]=d},a)},x=w(),y=w(),z=w(),A="[\\x20\\t\\r\\n\\f]",B="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",C=B.replace("w","w#"),D="([*^$|!~]?=)",E="\\["+A+"*("+B+")"+A+"*(?:"+D+A+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+C+")|)|)"+A+"*\\]",F=":("+B+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+E+")|[^:]|\\\\.)*|.*))\\)|)",G=":(nth|eq|gt|lt|first|last|even|odd)(?:\\(((?:-\\d)?\\d*)\\)|)(?=[^-]|$)",H=new RegExp("^"+A+"+|((?:^|[^\\\\])(?:\\\\.)*)"+A+"+$","g"),I=new RegExp("^"+A+"*,"+A+"*"),J=new RegExp("^"+A+"*([\\x20\\t\\r\\n\\f>+~])"+A+"*"),K=new RegExp(F),L=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,M=/^:not/,N=/[\x20\t\r\n\f]*[+~]/,O=/:not\($/,P=/h\d/i,Q=/input|select|textarea|button/i,R=/\\(?!\\)/g,S={ID:new RegExp("^#("+B+")"),CLASS:new RegExp("^\\.("+B+")"),NAME:new RegExp("^\\[name=['\"]?("+B+")['\"]?\\]"),TAG:new RegExp("^("+B.replace("w","w*")+")"),ATTR:new RegExp("^"+E),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+A+"*(even|odd|(([+-]|)(\\d*)n|)"+A+"*(?:([+-]|)"+A+"*(\\d+)|))"+A+"*\\)|)","i"),POS:new RegExp(G,"ig"),needsContext:new RegExp("^"+A+"*[>+~]|"+G,"i")},T=function(a){var b=q.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},U=T(function(a){return a.appendChild(q.createComment("")),!a.getElementsByTagName("*").length}),V=T(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),W=T(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),X=T(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),Y=T(function(a){a.id=o+0,a.innerHTML="<a name='"+o+"'></a><div name='"+o+"'></div>",r.insertBefore(a,r.firstChild);var b=q.getElementsByName&&q.getElementsByName(o).length===2+q.getElementsByName(o+0).length;return e=!q.getElementById(o),r.removeChild(a),b});try{t.call(r.childNodes,0)[0].nodeType}catch(Z){t=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}$.matches=function(a,b){return $(a,null,null,b)},$.matchesSelector=function(a,b){return $(b,null,null,[a]).length>0},g=$.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=g(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=g(b);return c},h=$.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},i=$.contains=r.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:r.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},$.attr=function(a,b){var c,d=h(a);return d||(b=b.toLowerCase()),f.attrHandle[b]?f.attrHandle[b](a):W||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},f=$.selectors={cacheLength:50,createPseudo:v,match:S,order:new RegExp("ID|TAG"+(Y?"|NAME":"")+(X?"|CLASS":"")),attrHandle:V?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:e?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:U?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(R,""),a[3]=(a[4]||a[5]||"").replace(R,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||$.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&$.error(a[0]),a},PSEUDO:function(a,b,c){var d,e;if(S.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(d=a[4])K.test(d)&&(e=bc(d,b,c,!0))&&(e=d.indexOf(")",d.length-e)-d.length)&&(d=d.slice(0,e),a[0]=a[0].slice(0,e)),a[2]=d;return a.slice(0,3)}},filter:{ID:e?function(a){return a=a.replace(R,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(R,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(R,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=x[o][a];return b||(b=x(a,new RegExp("(^|"+A+")"+a+"("+A+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=$.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return $.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=s++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[o]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[o]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e,g=f.pseudos[a]||f.pseudos[a.toLowerCase()];return g||$.error("unsupported pseudo: "+a),g[o]?g(b,c,d):g.length>1?(e=[a,a,"",b],function(a){return g(a,0,e)}):g}},pseudos:{not:v(function(a,b,c){var d=j(a.replace(H,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!f.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:v(function(a){return function(b){return(b.textContent||b.innerText||g(b)).indexOf(a)>-1}}),has:v(function(a){return function(b){return $(a,b).length>0}}),header:function(a){return P.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:_("radio"),checkbox:_("checkbox"),file:_("file"),password:_("password"),image:_("image"),submit:ba("submit"),reset:ba("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return Q.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},odd:function(a,b,c){var d=[],e=c?0:1,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},lt:function(a,b,c){return c?a.slice(+b):a.slice(0,+b)},gt:function(a,b,c){return c?a.slice(0,+b+1):a.slice(+b+1)},eq:function(a,b,c){var d=a.splice(+b,1);return c?a:d}}},k=r.compareDocumentPosition?function(a,b){return a===b?(l=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:function(a,b){if(a===b)return l=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,h=b.parentNode,i=g;if(g===h)return bb(a,b);if(!g)return-1;if(!h)return 1;while(i)e.unshift(i),i=i.parentNode;i=h;while(i)f.unshift(i),i=i.parentNode;c=e.length,d=f.length;for(var j=0;j<c&&j<d;j++)if(e[j]!==f[j])return bb(e[j],f[j]);return j===c?bb(a,f[j],-1):bb(e[j],b,1)},[0,0].sort(k),m=!l,$.uniqueSort=function(a){var b,c=1;l=m,a.sort(k);if(l)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1);return a},$.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},j=$.compile=function(a,b,c){var d,e,f,g=z[o][a];if(g&&g.context===b)return g;d=bc(a,b,c);for(e=0,f=d.length;e<f;e++)d[e]=bf(d[e],b,c);return g=z(a,bg(d)),g.context=b,g.runs=g.dirruns=0,g},q.querySelectorAll&&function(){var a,b=bk,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[],f=[":active"],g=r.matchesSelector||r.mozMatchesSelector||r.webkitMatchesSelector||r.oMatchesSelector||r.msMatchesSelector;T(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+A+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+A+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bk=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return u.apply(f,t.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j,k,l,m=d.getAttribute("id"),n=m||o,p=N.test(a)&&d.parentNode||d;m?n=n.replace(c,"\\$&"):d.setAttribute("id",n),j=bc(a,d,h),n="[id='"+n+"']";for(k=0,l=j.length;k<l;k++)j[k]=n+j[k].selector;try{return u.apply(f,t.call(p.querySelectorAll(j.join(",")),0)),f}catch(i){}finally{m||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push(S.PSEUDO.source,S.POS.source,"!=")}catch(c){}}),f=new RegExp(f.join("|")),$.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!h(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=g.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return $(c,null,null,[b]).length>0})}(),f.setFilters.nth=f.setFilters.eq,f.filters=f.pseudos,$.attr=p.attr,p.find=$,p.expr=$.selectors,p.expr[":"]=p.expr.pseudos,p.unique=$.uniqueSort,p.text=$.getText,p.isXMLDoc=$.isXML,p.contains=$.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={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,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.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=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{cj=f.href}catch(cy){cj=e.createElement("a"),cj.href="",cj=cj.href}ck=ct.exec(cj.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:cj,isLocal:cn.test(ck[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,ck[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==ck[1]&&i[2]==ck[2]&&(i[3]||(i[1]==="http:"?80:443))==(ck[3]||(ck[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cQ.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cT[c]=cT[c]||[],cT[c].unshift(b)},prefilter:function(a,b){b?cS.unshift(a):cS.push(a)}}),p.Tween=cZ,cZ.prototype={constructor:cZ,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||(p.cssNumber[c]?"":"px")},cur:function(){var a=cZ.propHooks[this.prop];return a&&a.get?a.get(this):cZ.propHooks._default.get(this)},run:function(a){var b,c=cZ.propHooks[this.prop];return this.options.duration?this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=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):cZ.propHooks._default.set(this),this}},cZ.prototype.init.prototype=cZ.prototype,cZ.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cZ.propHooks.scrollTop=cZ.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(c$(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bZ).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cW(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cR.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:c$("show"),slideUp:c$("hide"),slideToggle:c$("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cZ.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cO&&(cO=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cO),cO=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c_=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j,k,l,m=this[0],n=m&&m.ownerDocument;if(!n)return;return(e=n.body)===m?p.offset.bodyOffset(m):(d=n.documentElement,p.contains(d,m)?(c=m.getBoundingClientRect(),f=da(n),g=d.clientTop||e.clientTop||0,h=d.clientLeft||e.clientLeft||0,i=f.pageYOffset||d.scrollTop,j=f.pageXOffset||d.scrollLeft,k=c.top+i-g,l=c.left+j-h,{top:k,left:l}):{top:0,left:0})},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
test/A11yMain-test.js
vga-/a11y-eval-tool
/** * External dependencies */ import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; /** * Internal dependencies */ import A11yMain from '../src/containers/A11yMain.jsx'; import { ScanForm, SummaryTable, DetailedPanel } from '../src/components'; describe('<A11yMain />', () => { it('renders <ScanForm />', () => { const wrapper = shallow(<A11yMain />); expect(wrapper.find(ScanForm)).to.have.length(1); }); it('report type 1: does not render <SummaryTable /> if there is no report data', () => { const wrapper = shallow(<A11yMain />); wrapper.setState({ scanType: 1, reportData: [], }); expect(wrapper.find(SummaryTable)).to.have.length(0); }); it('report type 1: renders <SummaryTable /> if there is report data', () => { const wrapper = shallow(<A11yMain />); wrapper.setState({ scanType: 1, reportData: ['1', '2', '3'], }); expect(wrapper.find(SummaryTable)).to.have.length(1); }); it('report type 2: does not render <DetailedPanel /> if there is no report data', () => { const wrapper = shallow(<A11yMain />); wrapper.setState({ scanType: 2, reportData: [], }); expect(wrapper.find(DetailedPanel)).to.have.length(0); }); it('report type 2: renders <DetailedPanel /> if there is report data', () => { const wrapper = shallow(<A11yMain />); wrapper.setState({ scanType: 2, reportData: ['1', '2', '3'], }); expect(wrapper.find(DetailedPanel)).to.have.length(1); }); });
js/views/BackgroundView.js
SamyZ/TravelgramApp
import React from 'react'; import { Image } from 'react-native'; import backgroundStyles from '../styles/backgroundStyles'; import backgroundImage from '../../assets/background.jpg'; const propTypes = { children: React.PropTypes.any, }; const BackgroundView = props => ( <Image source={backgroundImage} style={backgroundStyles.imageContainer} > {props.children} </Image> ); BackgroundView.propTypes = propTypes; export default BackgroundView;
js/components/forecastitem.js
stage88/react-weather
/** * @flow */ 'use strict'; import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, } from 'react-native'; const renderForecastImage = require('./forecastimage'); type Props = { index: number; day: string; icon: string; low: string; high: string; separator: any; }; class ForecastItem extends Component { props: Props; constructor(props: Props) { super(props); } render() { var day = this.props.index === 1 ? 'Tomorrow' : this.props.day; return ( <View style={[styles.forecastItem, this.props.separator]}> <View stye={styles.forecastItemDayView}> <Text style={styles.dayText}>{ day }</Text> </View> <View style={styles.forecastItemDataView}> { renderForecastImage(this.props.icon, 22, 22) } <Text style={styles.forecastItemTempLow}>{ this.props.low }</Text> <Text style={styles.forecastItemTempHigh}>{ this.props.high }</Text> </View> </View> ); } } const styles = StyleSheet.create({ forecastItem: { paddingTop: 14, paddingBottom: 12, flexDirection: 'row' }, forecastItemDayView: { flex: 1 }, forecastItemDataView: { flex: 1, flexDirection: 'row', justifyContent: 'flex-end' }, dayText: { fontSize: 16 }, forecastItemTempLow: { textAlign: 'right', marginLeft: 16, width: 20, color: '#B0B5BF', fontSize: 16 }, forecastItemTempHigh: { textAlign: 'right', marginLeft: 16, width: 20, fontSize: 16 } }); module.exports = ForecastItem;
ajax/libs/ember-data.js/2.9.0-beta.4/ember-data.js
holtkamp/cdnjs
(function(){ "use strict"; /*! * @overview Ember Data * @copyright Copyright 2011-2016 Tilde Inc. and contributors. * Portions Copyright 2011 LivingSocial Inc. * @license Licensed under MIT license (see license.js) * @version 2.9.0-beta.4 */ var loader, define, requireModule, require, requirejs; (function(global) { 'use strict'; var stats; // Save off the original values of these globals, so we can restore them if someone asks us to var oldGlobals = { loader: loader, define: define, requireModule: requireModule, require: require, requirejs: requirejs }; requirejs = require = requireModule = function(name) { stats.require++; var pending = []; var mod = findModule(name, '(require)', pending); for (var i = pending.length - 1; i >= 0; i--) { pending[i].exports(); } return mod.module.exports; }; function resetStats() { stats = { define: 0, require: 0, reify: 0, findDeps: 0, modules: 0, exports: 0, resolve: 0, resolveRelative: 0, findModule: 0, pendingQueueLength: 0 }; requirejs._stats = stats; } resetStats(); loader = { noConflict: function(aliases) { var oldName, newName; for (oldName in aliases) { if (aliases.hasOwnProperty(oldName)) { if (oldGlobals.hasOwnProperty(oldName)) { newName = aliases[oldName]; global[newName] = global[oldName]; global[oldName] = oldGlobals[oldName]; } } } } }; var _isArray; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { _isArray = Array.isArray; } var registry = {}; var seen = {}; var uuid = 0; function unsupportedModule(length) { throw new Error('an unsupported module was defined, expected `define(name, deps, module)` instead got: `' + length + '` arguments to define`'); } var defaultDeps = ['require', 'exports', 'module']; function Module(name, deps, callback, alias) { stats.modules++; this.id = uuid++; this.name = name; this.deps = !deps.length && callback.length ? defaultDeps : deps; this.module = { exports: {} }; this.callback = callback; this.finalized = false; this.hasExportsAsDep = false; this.isAlias = alias; this.reified = new Array(deps.length); this._foundDeps = false; this.isPending = false; } Module.prototype.makeDefaultExport = function() { var exports = this.module.exports; if (exports !== null && (typeof exports === 'object' || typeof exports === 'function') && exports['default'] === undefined) { exports['default'] = exports; } }; Module.prototype.exports = function() { if (this.finalized) { return this.module.exports; } stats.exports++; this.finalized = true; this.isPending = false; if (loader.wrapModules) { this.callback = loader.wrapModules(this.name, this.callback); } this.reify(); var result = this.callback.apply(this, this.reified); if (!(this.hasExportsAsDep && result === undefined)) { this.module.exports = result; } this.makeDefaultExport(); return this.module.exports; }; Module.prototype.unsee = function() { this.finalized = false; this._foundDeps = false; this.isPending = false; this.module = { exports: {} }; }; Module.prototype.reify = function() { stats.reify++; var reified = this.reified; for (var i = 0; i < reified.length; i++) { var mod = reified[i]; reified[i] = mod.exports ? mod.exports : mod.module.exports(); } }; Module.prototype.findDeps = function(pending) { if (this._foundDeps) { return; } stats.findDeps++; this._foundDeps = true; this.isPending = true; var deps = this.deps; for (var i = 0; i < deps.length; i++) { var dep = deps[i]; var entry = this.reified[i] = { exports: undefined, module: undefined }; if (dep === 'exports') { this.hasExportsAsDep = true; entry.exports = this.module.exports; } else if (dep === 'require') { entry.exports = this.makeRequire(); } else if (dep === 'module') { entry.exports = this.module; } else { entry.module = findModule(resolve(dep, this.name), this.name, pending); } } }; Module.prototype.makeRequire = function() { var name = this.name; var r = function(dep) { return require(resolve(dep, name)); }; r['default'] = r; r.has = function(dep) { return has(resolve(dep, name)); }; return r; }; define = function(name, deps, callback) { stats.define++; if (arguments.length < 2) { unsupportedModule(arguments.length); } if (!_isArray(deps)) { callback = deps; deps = []; } if (callback instanceof Alias) { registry[name] = new Module(callback.name, deps, callback, true); } else { registry[name] = new Module(name, deps, callback, false); } }; // we don't support all of AMD // define.amd = {}; // we will support petals... define.petal = { }; function Alias(path) { this.name = path; } define.alias = function(path) { return new Alias(path); }; function missingModule(name, referrer) { throw new Error('Could not find module `' + name + '` imported from `' + referrer + '`'); } function findModule(name, referrer, pending) { stats.findModule++; var mod = registry[name] || registry[name + '/index']; while (mod && mod.isAlias) { mod = registry[mod.name]; } if (!mod) { missingModule(name, referrer); } if (pending && !mod.finalized && !mod.isPending) { mod.findDeps(pending); pending.push(mod); stats.pendingQueueLength++; } return mod; } function resolve(child, name) { stats.resolve++; if (child.charAt(0) !== '.') { return child; } stats.resolveRelative++; var parts = child.split('/'); var nameParts = name.split('/'); var parentBase = nameParts.slice(0, -1); for (var i = 0, l = parts.length; i < l; i++) { var part = parts[i]; if (part === '..') { if (parentBase.length === 0) { throw new Error('Cannot access parent module of root'); } parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join('/'); } function has(name) { return !!(registry[name] || registry[name + '/index']); } requirejs.entries = requirejs._eak_seen = registry; requirejs.has = has; requirejs.unsee = function(moduleName) { findModule(moduleName, '(unsee)', false).unsee(); }; requirejs.clear = function() { resetStats(); requirejs.entries = requirejs._eak_seen = registry = {}; seen = {}; }; // prime define('foo', function() {}); define('foo/bar', [], function() {}); define('foo/asdf', ['module', 'exports', 'require'], function(module, exports, require) { if (require.has('foo/bar')) { require('foo/bar'); } }); define('foo/baz', [], define.alias('foo')); define('foo/quz', define.alias('foo')); define('foo/bar', ['foo', './quz', './baz', './asdf', './bar', '../foo'], function() {}); define('foo/main', ['foo/bar'], function() {}); require('foo/main'); require.unsee('foo/bar'); requirejs.clear(); if (typeof exports === 'object' && typeof module === 'object' && module.exports) { module.exports = { require: require, define: define }; } })(this); define("ember-data/-private/adapters", ["exports", "ember-data/adapters/json-api", "ember-data/adapters/rest"], function (exports, _emberDataAdaptersJsonApi, _emberDataAdaptersRest) { exports.JSONAPIAdapter = _emberDataAdaptersJsonApi.default; exports.RESTAdapter = _emberDataAdaptersRest.default; }); /** @module ember-data */ define('ember-data/-private/adapters/build-url-mixin', ['exports', 'ember'], function (exports, _ember) { var get = _ember.default.get; /** WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 ## Using BuildURLMixin To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. The default behaviour is designed for RESTAdapter. ### Example ```javascript export default DS.Adapter.extend(BuildURLMixin, { findRecord: function(store, type, id, snapshot) { var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); return this.ajax(url, 'GET'); } }); ``` ### Attributes The `host` and `namespace` attributes will be used if defined, and are optional. @class BuildURLMixin @namespace DS */ exports.default = _ember.default.Mixin.create({ /** 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 `/`. When called by RESTAdapter.findMany() the `id` and `snapshot` parameters will be arrays of ids and snapshots. @method buildURL @param {String} modelName @param {(String|Array|Object)} id single id or array of ids or query @param {(DS.Snapshot|Array)} snapshot single snapshot or array of snapshots @param {String} requestType @param {Object} query object of query parameters to send for query requests. @return {String} url */ buildURL: function (modelName, id, snapshot, requestType, query) { switch (requestType) { case 'findRecord': return this.urlForFindRecord(id, modelName, snapshot); case 'findAll': return this.urlForFindAll(modelName, snapshot); case 'query': return this.urlForQuery(query, modelName); case 'queryRecord': return this.urlForQueryRecord(query, modelName); case 'findMany': return this.urlForFindMany(id, modelName, snapshot); case 'findHasMany': return this.urlForFindHasMany(id, modelName, snapshot); case 'findBelongsTo': return this.urlForFindBelongsTo(id, modelName, snapshot); case 'createRecord': return this.urlForCreateRecord(modelName, snapshot); case 'updateRecord': return this.urlForUpdateRecord(id, modelName, snapshot); case 'deleteRecord': return this.urlForDeleteRecord(id, modelName, snapshot); default: return this._buildURL(modelName, id); } }, /** @method _buildURL @private @param {String} modelName @param {String} id @return {String} url */ _buildURL: function (modelName, id) { var url = []; var host = get(this, 'host'); var prefix = this.urlPrefix(); var path; if (modelName) { path = this.pathForType(modelName); if (path) { url.push(path); } } if (id) { url.push(encodeURIComponent(id)); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url && url.charAt(0) !== '/') { url = '/' + url; } return url; }, /** * @method urlForFindRecord * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForFindRecord: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForFindAll * @param {String} modelName * @param {DS.SnapshotRecordArray} snapshot * @return {String} url */ urlForFindAll: function (modelName, snapshot) { return this._buildURL(modelName); }, /** * @method urlForQuery * @param {Object} query * @param {String} modelName * @return {String} url */ urlForQuery: function (query, modelName) { return this._buildURL(modelName); }, /** * @method urlForQueryRecord * @param {Object} query * @param {String} modelName * @return {String} url */ urlForQueryRecord: function (query, modelName) { return this._buildURL(modelName); }, /** * @method urlForFindMany * @param {Array} ids * @param {String} modelName * @param {Array} snapshots * @return {String} url */ urlForFindMany: function (ids, modelName, snapshots) { return this._buildURL(modelName); }, /** * @method urlForFindHasMany * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForFindHasMany: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForFindBelongsTo * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForFindBelongsTo: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForCreateRecord * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForCreateRecord: function (modelName, snapshot) { return this._buildURL(modelName); }, /** * @method urlForUpdateRecord * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForUpdateRecord: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForDeleteRecord * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForDeleteRecord: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** @method urlPrefix @private @param {String} path @param {String} parentURL @return {String} urlPrefix */ urlPrefix: function (path, parentURL) { var host = get(this, 'host'); var namespace = get(this, 'namespace'); if (!host || host === '/') { host = ''; } if (path) { // Protocol relative url if (/^\/\//.test(path) || /http(s)?:\/\//.test(path)) { // Do nothing, the full host is already included. return path; // Absolute path } else if (path.charAt(0) === '/') { return '' + host + path; // Relative path } else { return parentURL + '/' + path; } } // No path provided var url = []; if (host) { url.push(host); } if (namespace) { url.push(namespace); } 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/". ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ pathForType: function(modelName) { var decamelized = Ember.String.decamelize(modelName); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} modelName @return {String} path **/ pathForType: function (modelName) { var camelized = _ember.default.String.camelize(modelName); return _ember.default.String.pluralize(camelized); } }); }); define('ember-data/-private/core', ['exports', 'ember', 'ember-data/version'], function (exports, _ember, _emberDataVersion) { /** @module ember-data */ /** All Ember Data classes, methods and functions are defined inside of this namespace. @class DS @static */ /** @property VERSION @type String @static */ var DS = _ember.default.Namespace.create({ VERSION: _emberDataVersion.default, name: "DS" }); if (_ember.default.libraries) { _ember.default.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } exports.default = DS; }); define('ember-data/-private/debug', ['exports', 'ember'], function (exports, _ember) { exports.assert = assert; exports.debug = debug; exports.deprecate = deprecate; exports.info = info; exports.runInDebug = runInDebug; exports.warn = warn; exports.debugSeal = debugSeal; exports.assertPolymorphicType = assertPolymorphicType; function assert() { return _ember.default.assert.apply(_ember.default, arguments); } function debug() { return _ember.default.debug.apply(_ember.default, arguments); } function deprecate() { return _ember.default.deprecate.apply(_ember.default, arguments); } function info() { return _ember.default.info.apply(_ember.default, arguments); } function runInDebug() { return _ember.default.runInDebug.apply(_ember.default, arguments); } function warn() { return _ember.default.warn.apply(_ember.default, arguments); } function debugSeal() { return _ember.default.debugSeal.apply(_ember.default, arguments); } function checkPolymorphic(typeClass, addedRecord) { if (typeClass.__isMixin) { //TODO Need to do this in order to support mixins, should convert to public api //once it exists in Ember return typeClass.__mixin.detect(addedRecord.type.PrototypeMixin); } if (_ember.default.MODEL_FACTORY_INJECTIONS) { typeClass = typeClass.superclass; } return typeClass.detect(addedRecord.type); } /* Assert that `addedRecord` has a valid type so it can be added to the relationship of the `record`. The assert basically checks if the `addedRecord` can be added to the relationship (specified via `relationshipMeta`) of the `record`. This utility should only be used internally, as both record parameters must be an InternalModel and the `relationshipMeta` needs to be the meta information about the relationship, retrieved via `record.relationshipFor(key)`. @method assertPolymorphicType @param {InternalModel} record @param {RelationshipMeta} relationshipMeta retrieved via `record.relationshipFor(key)` @param {InternalModel} addedRecord record which should be added/set for the relationship */ function assertPolymorphicType(record, relationshipMeta, addedRecord) { var addedType = addedRecord.type.modelName; var recordType = record.type.modelName; var key = relationshipMeta.key; var typeClass = record.store.modelFor(relationshipMeta.type); var assertionMessage = 'You cannot add a record of type \'' + addedType + '\' to the \'' + recordType + '.' + key + '\' relationship (only \'' + typeClass.modelName + '\' allowed)'; assert(assertionMessage, checkPolymorphic(typeClass, addedRecord)); } }); define('ember-data/-private/ext/date', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { /** 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 @deprecated */ _ember.default.Date = _ember.default.Date || {}; var origParse = Date.parse; var numericKeys = [1, 4, 5, 6, 7, 10, 11]; var parseDate = function (date) { var timestamp, struct; var 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; }; exports.parseDate = parseDate; _ember.default.Date.parse = function (date) { // throw deprecation (0, _emberDataPrivateDebug.deprecate)('Ember.Date.parse is deprecated because Safari 5-, IE8-, and\n Firefox 3.6- are no longer supported (see\n https://github.com/csnover/js-iso8601 for the history of this issue).\n Please use Date.parse instead', false, { id: 'ds.ember.date.parse-deprecate', until: '3.0.0' }); return parseDate(date); }; if (_ember.default.EXTEND_PROTOTYPES === true || _ember.default.EXTEND_PROTOTYPES.Date) { (0, _emberDataPrivateDebug.deprecate)('Overriding Date.parse with Ember.Date.parse is deprecated. Please set ENV.EmberENV.EXTEND_PROTOTYPES.Date to false in config/environment.js\n\n\n// config/environment.js\nENV = {\n EmberENV: {\n EXTEND_PROTOTYPES: {\n Date: false,\n }\n }\n}\n', false, { id: 'ds.date.parse-deprecate', until: '3.0.0' }); Date.parse = parseDate; } }); /** @module ember-data */ define('ember-data/-private/features', ['exports', 'ember'], function (exports, _ember) { exports.default = isEnabled; function isEnabled() { var _Ember$FEATURES; return (_Ember$FEATURES = _ember.default.FEATURES).isEnabled.apply(_Ember$FEATURES, arguments); } }); define('ember-data/-private/global', ['exports'], function (exports) { /* globals global, window, self */ // originally from https://github.com/emberjs/ember.js/blob/c0bd26639f50efd6a03ee5b87035fd200e313b8e/packages/ember-environment/lib/global.js // from lodash to catch fake globals function checkGlobal(value) { return value && value.Object === Object ? value : undefined; } // element ids can ruin global miss checks function checkElementIdShadowing(value) { return value && value.nodeType === undefined ? value : undefined; } // export real global exports.default = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || new Function('return this')(); // eval outside of strict mode }); define("ember-data/-private/initializers/data-adapter", ["exports", "ember-data/-private/system/debug/debug-adapter"], function (exports, _emberDataPrivateSystemDebugDebugAdapter) { exports.default = initializeDebugAdapter; /* Configures a registry with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeDebugAdapter @param {Ember.Registry} registry */ function initializeDebugAdapter(registry) { registry.register('data-adapter:main', _emberDataPrivateSystemDebugDebugAdapter.default); } }); define('ember-data/-private/initializers/store-injections', ['exports'], function (exports) { exports.default = initializeStoreInjections; /* Configures a registry with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Registry} registry */ function initializeStoreInjections(registry) { // registry.injection for Ember < 2.1.0 // application.inject for Ember 2.1.0+ var inject = registry.inject || registry.injection; inject.call(registry, 'controller', 'store', 'service:store'); inject.call(registry, 'route', 'store', 'service:store'); inject.call(registry, 'data-adapter', 'store', 'service:store'); } }); define("ember-data/-private/initializers/store", ["exports", "ember-data/-private/system/store", "ember-data/-private/serializers", "ember-data/-private/adapters"], function (exports, _emberDataPrivateSystemStore, _emberDataPrivateSerializers, _emberDataPrivateAdapters) { exports.default = initializeStore; function has(applicationOrRegistry, fullName) { if (applicationOrRegistry.has) { // < 2.1.0 return applicationOrRegistry.has(fullName); } else { // 2.1.0+ return applicationOrRegistry.hasRegistration(fullName); } } /* Configures a registry for use with an Ember-Data store. Accepts an optional namespace argument. @method initializeStore @param {Ember.Registry} registry */ function initializeStore(registry) { // registry.optionsForType for Ember < 2.1.0 // application.registerOptionsForType for Ember 2.1.0+ var registerOptionsForType = registry.registerOptionsForType || registry.optionsForType; registerOptionsForType.call(registry, 'serializer', { singleton: false }); registerOptionsForType.call(registry, 'adapter', { singleton: false }); registry.register('serializer:-default', _emberDataPrivateSerializers.JSONSerializer); registry.register('serializer:-rest', _emberDataPrivateSerializers.RESTSerializer); registry.register('adapter:-rest', _emberDataPrivateAdapters.RESTAdapter); registry.register('adapter:-json-api', _emberDataPrivateAdapters.JSONAPIAdapter); registry.register('serializer:-json-api', _emberDataPrivateSerializers.JSONAPISerializer); if (!has(registry, 'service:store')) { registry.register('service:store', _emberDataPrivateSystemStore.default); } } }); define('ember-data/-private/initializers/transforms', ['exports', 'ember-data/-private/transforms'], function (exports, _emberDataPrivateTransforms) { exports.default = initializeTransforms; /* Configures a registry for use with Ember-Data transforms. @method initializeTransforms @param {Ember.Registry} registry */ function initializeTransforms(registry) { registry.register('transform:boolean', _emberDataPrivateTransforms.BooleanTransform); registry.register('transform:date', _emberDataPrivateTransforms.DateTransform); registry.register('transform:number', _emberDataPrivateTransforms.NumberTransform); registry.register('transform:string', _emberDataPrivateTransforms.StringTransform); } }); define('ember-data/-private/instance-initializers/initialize-store-service', ['exports'], function (exports) { exports.default = initializeStoreService; /* Configures a registry for use with an Ember-Data store. @method initializeStoreService @param {Ember.ApplicationInstance} applicationOrRegistry */ function initializeStoreService(application) { var container = application.lookup ? application : application.container; // Eagerly generate the store so defaultStore is populated. container.lookup('service:store'); } }); define("ember-data/-private/serializers", ["exports", "ember-data/serializers/json-api", "ember-data/serializers/json", "ember-data/serializers/rest"], function (exports, _emberDataSerializersJsonApi, _emberDataSerializersJson, _emberDataSerializersRest) { exports.JSONAPISerializer = _emberDataSerializersJsonApi.default; exports.JSONSerializer = _emberDataSerializersJson.default; exports.RESTSerializer = _emberDataSerializersRest.default; }); /** @module ember-data */ define("ember-data/-private/system/clone-null", ["exports", "ember-data/-private/system/empty-object"], function (exports, _emberDataPrivateSystemEmptyObject) { exports.default = cloneNull; function cloneNull(source) { var clone = new _emberDataPrivateSystemEmptyObject.default(); for (var key in source) { clone[key] = source[key]; } return clone; } }); define('ember-data/-private/system/coerce-id', ['exports'], function (exports) { exports.default = coerceId; // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.findRecord('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 || id === undefined || id === '' ? null : id + ''; } }); define("ember-data/-private/system/debug", ["exports", "ember-data/-private/system/debug/debug-adapter"], function (exports, _emberDataPrivateSystemDebugDebugAdapter) { exports.default = _emberDataPrivateSystemDebugDebugAdapter.default; }); /** @module ember-data */ define('ember-data/-private/system/debug/debug-adapter', ['exports', 'ember', 'ember-data/model'], function (exports, _ember, _emberDataModel) { var get = _ember.default.get; var capitalize = _ember.default.String.capitalize; var underscore = _ember.default.String.underscore; var assert = _ember.default.assert; /* Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ exports.default = _ember.default.DataAdapter.extend({ getFilters: function () { return [{ name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' }]; }, detect: function (typeClass) { return typeClass !== _emberDataModel.default && _emberDataModel.default.detect(typeClass); }, columnsForType: function (typeClass) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; get(typeClass, 'attributes').forEach(function (meta, name) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function (modelClass, modelName) { if (arguments.length < 2) { // Legacy Ember.js < 1.13 support var containerKey = modelClass._debugContainerKey; if (containerKey) { var match = containerKey.match(/model:(.*)/); if (match) { modelName = match[1]; } } } assert("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support", !!modelName); return this.get('store').peekAll(modelName); }, getRecordColumnValues: function (record) { var _this = this; var count = 0; var columnValues = { id: get(record, 'id') }; record.eachAttribute(function (key) { if (count++ > _this.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function (record) { var keywords = []; var keys = _ember.default.A(['id']); record.eachAttribute(function (key) { return keys.push(key); }); keys.forEach(function (key) { return keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function (record) { return { isNew: record.get('isNew'), isModified: record.get('hasDirtyAttributes') && !record.get('isNew'), isClean: !record.get('hasDirtyAttributes') }; }, getRecordColor: function (record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('hasDirtyAttributes')) { color = 'blue'; } return color; }, observeRecord: function (record, recordUpdated) { var releaseMethods = _ember.default.A(); var keysToObserve = _ember.default.A(['id', 'isNew', 'hasDirtyAttributes']); record.eachAttribute(function (key) { return keysToObserve.push(key); }); var adapter = this; keysToObserve.forEach(function (key) { var handler = function () { recordUpdated(adapter.wrapRecord(record)); }; _ember.default.addObserver(record, key, handler); releaseMethods.push(function () { _ember.default.removeObserver(record, key, handler); }); }); var release = function () { releaseMethods.forEach(function (fn) { return fn(); }); }; return release; } }); }); /** @module ember-data */ define('ember-data/-private/system/debug/debug-info', ['exports', 'ember'], function (exports, _ember) { exports.default = _ember.default.Mixin.create({ /** 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']; var relationships = { belongsTo: [], hasMany: [] }; var expensiveProperties = []; this.eachAttribute(function (name, meta) { return attributes.push(name); }); 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', 'hasDirtyAttributes', '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 } }; } }); }); define("ember-data/-private/system/empty-object", ["exports"], function (exports) { exports.default = EmptyObject; // This exists because `Object.create(null)` is absurdly slow compared // to `new EmptyObject()`. In either case, you want a null prototype // when you're treating the object instances as arbitrary dictionaries // and don't want your keys colliding with build-in methods on the // default object prototype. var proto = Object.create(null, { // without this, we will always still end up with (new // EmptyObject()).constructor === Object constructor: { value: undefined, enumerable: false, writable: true } }); function EmptyObject() {} EmptyObject.prototype = proto; }); define('ember-data/-private/system/is-array-like', ['exports', 'ember'], function (exports, _ember) { exports.default = isArrayLike; /* We're using this to detect arrays and "array-like" objects. This is a copy of the `isArray` method found in `ember-runtime/utils` as we're currently unable to import non-exposed modules. This method was previously exposed as `Ember.isArray` but since https://github.com/emberjs/ember.js/pull/11463 `Ember.isArray` is an alias of `Array.isArray` hence removing the "array-like" part. */ function isArrayLike(obj) { if (!obj || obj.setInterval) { return false; } if (Array.isArray(obj)) { return true; } if (_ember.default.Array.detect(obj)) { return true; } var type = _ember.default.typeOf(obj); if ('array' === type) { return true; } if (obj.length !== undefined && 'object' === type) { return true; } return false; } }); define("ember-data/-private/system/many-array", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/store/common"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStoreCommon) { var get = _ember.default.get; var set = _ember.default.set; /** A `ManyArray` is a `MutableArray` 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: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default 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 Ember.Object @uses Ember.MutableArray, Ember.Evented */ exports.default = _ember.default.Object.extend(_ember.default.MutableArray, _ember.default.Evented, { init: function () { this._super.apply(this, arguments); this.currentState = _ember.default.A([]); }, record: null, canonicalState: null, currentState: null, length: 0, objectAt: function (index) { //Ember observers such as 'firstObject', 'lastObject' might do out of bounds accesses if (!this.currentState[index]) { return undefined; } return this.currentState[index].getRecord(); }, flushCanonical: function () { //TODO make this smarter, currently its plenty stupid var toSet = this.canonicalState.filter(function (internalModel) { return !internalModel.isDeleted(); }); //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = this.currentState.filter( // only add new records which are not yet in the canonical state of this // relationship (a new record can be in the canonical state if it has // been 'acknowleged' to be in the relationship via a store.push) function (internalModel) { return internalModel.isNew() && toSet.indexOf(internalModel) === -1; }); toSet = toSet.concat(newRecords); var oldLength = this.length; this.arrayContentWillChange(0, this.length, toSet.length); // It’s possible the parent side of the relationship may have been unloaded by this point if ((0, _emberDataPrivateSystemStoreCommon._objectIsAlive)(this)) { this.set('length', toSet.length); } this.currentState = toSet; this.arrayContentDidChange(0, oldLength, this.length); //TODO Figure out to notify only on additions and maybe only if unloaded this.relationship.notifyHasManyChanged(); this.record.updateRecordArrays(); }, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, /** The loading state of this array @property {Boolean} isLoaded */ isLoaded: false, /** The relationship which manages this array. @property {ManyRelationship} relationship @private */ relationship: null, /** Metadata associated with the request for async hasMany relationships. Example Given that the server returns the following JSON payload when fetching a hasMany relationship: ```js { "comments": [{ "id": 1, "comment": "This is the first comment", }, { // ... }], "meta": { "page": 1, "total": 5 } } ``` You can then access the metadata via the `meta` property: ```js post.get('comments').then(function(comments) { var meta = comments.get('meta'); // meta.page => 1 // meta.total => 5 }); ``` @property {Object} meta @public */ meta: null, internalReplace: function (idx, amt, objects) { if (!objects) { objects = []; } this.arrayContentWillChange(idx, amt, objects.length); this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects)); this.set('length', this.currentState.length); this.arrayContentDidChange(idx, amt, objects.length); if (objects) { //TODO(Igor) probably needed only for unloaded records this.relationship.notifyHasManyChanged(); } this.record.updateRecordArrays(); }, //TODO(Igor) optimize internalRemoveRecords: function (records) { var index; for (var i = 0; i < records.length; i++) { index = this.currentState.indexOf(records[i]); this.internalReplace(index, 1); } }, //TODO(Igor) optimize internalAddRecords: function (records, idx) { if (idx === undefined) { idx = this.currentState.length; } this.internalReplace(idx, 0, records); }, replace: function (idx, amt, objects) { var records; if (amt > 0) { records = this.currentState.slice(idx, idx + amt); this.get('relationship').removeRecords(records); } if (objects) { this.get('relationship').addRecords(objects.map(function (obj) { return obj._internalModel; }), idx); } }, /** 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 reload @public */ reload: function () { return this.relationship.reload(); }, /** Saves all of the records in the `ManyArray`. Example ```javascript store.findRecord('inbox', 1).then(function(inbox) { inbox.get('messages').then(function(messages) { messages.forEach(function(message) { message.set('isRead', true); }); messages.save() }); }); ``` @method save @return {DS.PromiseArray} promise */ save: function () { var manyArray = this; var promiseLabel = "DS: ManyArray#save " + get(this, 'type'); var promise = _ember.default.RSVP.all(this.invoke("save"), promiseLabel).then(function (array) { return manyArray; }, null, "DS: ManyArray#save return ManyArray"); return _emberDataPrivateSystemPromiseProxies.PromiseArray.create({ promise: promise }); }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function (hash) { var store = get(this, 'store'); var type = get(this, 'type'); var record; (0, _emberDataPrivateDebug.assert)("You cannot add '" + type.modelName + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic')); record = store.createRecord(type.modelName, hash); this.pushObject(record); return record; } }); }); /** @module ember-data */ define("ember-data/-private/system/model", ["exports", "ember-data/-private/system/model/model", "ember-data/attr", "ember-data/-private/system/model/states", "ember-data/-private/system/model/errors"], function (exports, _emberDataPrivateSystemModelModel, _emberDataAttr, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemModelErrors) { exports.RootState = _emberDataPrivateSystemModelStates.default; exports.attr = _emberDataAttr.default; exports.Errors = _emberDataPrivateSystemModelErrors.default; exports.default = _emberDataPrivateSystemModelModel.default; }); /** @module ember-data */ define("ember-data/-private/system/model/attr", ["exports", "ember", "ember-data/-private/debug"], function (exports, _ember, _emberDataPrivateDebug) { var get = _ember.default.get; var Map = _ember.default.Map; /** @module ember-data */ /** @class Model @namespace DS */ var AttrClassMethodsMixin = _ember.default.Mixin.create({ /** 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 ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; var attributes = Ember.get(Person, 'attributes') attributes.forEach(function(meta, name) { 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.default.computed(function () { var _this = this; var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isAttribute) { (0, _emberDataPrivateDebug.assert)("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + _this.toString(), name !== 'id'); meta.name = name; map.set(name, meta); } }); return map; }).readOnly(), /** 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 ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; var transformedAttributes = Ember.get(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.default.computed(function () { var map = Map.create(); this.eachAttribute(function (key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }).readOnly(), /** 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 import DS from 'ember-data'; var Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); 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} [binding] the value to which the callback's `this` should be bound @static */ eachAttribute: function (callback, binding) { get(this, 'attributes').forEach(function (meta, name) { callback.call(binding, name, meta); }); }, /** 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 import DS from 'ember-data'; var Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); 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} [binding] the value to which the callback's `this` should be bound @static */ eachTransformedAttribute: function (callback, binding) { get(this, 'transformedAttributes').forEach(function (type, name) { callback.call(binding, name, type); }); } }); exports.AttrClassMethodsMixin = AttrClassMethodsMixin; var AttrInstanceMethodsMixin = _ember.default.Mixin.create({ eachAttribute: function (callback, binding) { this.constructor.eachAttribute(callback, binding); } }); exports.AttrInstanceMethodsMixin = AttrInstanceMethodsMixin; }); define('ember-data/-private/system/model/errors', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { var get = _ember.default.get; var set = _ember.default.set; var isEmpty = _ember.default.isEmpty; var makeArray = _ember.default.makeArray; var MapWithDefault = _ember.default.MapWithDefault; /** @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 a `User` model that looked like this: ```app/models/user.js import DS from 'ember-data'; export default 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 would be expected to return an error response that described the problem, so that error messages can be generated on the app. API responses will be translated into instances of `DS.Errors` differently, depending on the specific combination of adapter and serializer used. You may want to check the documentation or the source code of the libraries that you are using, to know how they expect errors to be communicated. Errors can be displayed to the user by accessing their property name to get an array of all the error objects for that property. Each error object is a JavaScript object with two keys: - `message` A string containing the error message from the backend - `attribute` The name of the property associated with this error message ```handlebars <label>Username: {{input value=username}} </label> {{#each model.errors.username as |error|}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each model.errors.email as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` You can also access the special `messages` property on the error object to get an array of all the error strings. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @class Errors @namespace DS @extends Ember.Object @uses Ember.Enumerable @uses Ember.Evented */ exports.default = _ember.default.ArrayProxy.extend(_ember.default.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid @deprecated */ registerHandlers: function (target, becameInvalid, becameValid) { (0, _emberDataPrivateDebug.deprecate)('Record errors will no longer be evented.', false, { id: 'ds.errors.registerHandlers', until: '3.0.0' }); this._registerHandlers(target, becameInvalid, becameValid); }, /** Register with target handler @method _registerHandlers @private */ _registerHandlers: function (target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: _ember.default.computed(function () { return MapWithDefault.create({ defaultValue: function () { return _ember.default.A(); } }); }), /** 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'); // returns: // [{attribute: "email", message: "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 model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @property messages @type {Array} */ messages: _ember.default.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: _ember.default.computed(function () { return _ember.default.A(); }), /** @method unknownProperty @private */ unknownProperty: function (attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** Total number of errors. @property length @type {Number} @readOnly */ /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: _ember.default.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 @deprecated */ add: function (attribute, messages) { (0, _emberDataPrivateDebug.warn)('Interacting with a record errors object will no longer change the record state.', false, { id: 'ds.errors.add' }); var wasEmpty = get(this, 'isEmpty'); this._add(attribute, messages); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** Adds error messages to a given attribute without sending event. @method _add @private */ _add: function (attribute, messages) { messages = this._findOrCreateMessages(attribute, messages); this.addObjects(messages); get(this, 'errorsByAttributeName').get(attribute).addObjects(messages); this.notifyPropertyChange(attribute); }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function (attribute, messages) { var errors = this.errorsFor(attribute); var messagesArray = makeArray(messages); var _messages = new Array(messagesArray.length); for (var i = 0; i < messagesArray.length; i++) { var message = messagesArray[i]; var err = errors.findBy('message', message); if (err) { _messages[i] = err; } else { _messages[i] = { attribute: attribute, message: message }; } } return _messages; }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. Example: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ email: DS.attr('string'), twoFactorAuth: DS.attr('boolean'), phone: DS.attr('string') }); ``` ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { save: function(user) { if (!user.get('twoFactorAuth')) { user.get('errors').remove('phone'); } user.save(); } } }); ``` @method remove @param {String} attribute @deprecated */ remove: function (attribute) { (0, _emberDataPrivateDebug.warn)('Interacting with a record errors object will no longer change the record state.', false, { id: 'ds.errors.remove' }); if (get(this, 'isEmpty')) { return; } this._remove(attribute); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages from the given attribute without sending event. @method _remove @private */ _remove: function (attribute) { if (get(this, 'isEmpty')) { return; } var content = this.rejectBy('attribute', attribute); set(this, 'content', content); get(this, 'errorsByAttributeName').delete(attribute); this.notifyPropertyChange(attribute); }, /** Removes all error messages and sends `becameValid` event to the record. Example: ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { retrySave: function(user) { user.get('errors').clear(); user.save(); } } }); ``` @method clear @deprecated */ clear: function () { (0, _emberDataPrivateDebug.warn)('Interacting with a record errors object will no longer change the record state.', false, { id: 'ds.errors.clear' }); if (get(this, 'isEmpty')) { return; } this._clear(); this.trigger('becameValid'); }, /** Removes all error messages. to the record. @method _clear @private */ _clear: function () { if (get(this, 'isEmpty')) { return; } var errorsByAttributeName = get(this, 'errorsByAttributeName'); var attributes = _ember.default.A(); errorsByAttributeName.forEach(function (_, attribute) { attributes.push(attribute); }); errorsByAttributeName.clear(); attributes.forEach(function (attribute) { this.notifyPropertyChange(attribute); }, this); _ember.default.ArrayProxy.prototype.clear.call(this); }, /** Checks if there is error messages for the given attribute. ```app/routes/user/edit.js import Ember from 'ember'; export default 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)); } }); }); define("ember-data/-private/system/model/internal-model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/model/states", "ember-data/-private/system/relationships/state/create", "ember-data/-private/system/snapshot", "ember-data/-private/system/empty-object", "ember-data/-private/features", "ember-data/-private/utils", "ember-data/-private/system/references"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemRelationshipsStateCreate, _emberDataPrivateSystemSnapshot, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures, _emberDataPrivateUtils, _emberDataPrivateSystemReferences) { var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; })(); exports.default = InternalModel; var Promise = _ember.default.RSVP.Promise; var get = _ember.default.get; var set = _ember.default.set; var copy = _ember.default.copy; var assign = _ember.default.assign || _ember.default.merge; var _extractPivotNameCache = new _emberDataPrivateSystemEmptyObject.default(); var _splitOnDotCache = new _emberDataPrivateSystemEmptyObject.default(); function splitOnDot(name) { return _splitOnDotCache[name] || (_splitOnDotCache[name] = name.split('.')); } function extractPivotName(name) { return _extractPivotNameCache[name] || (_extractPivotNameCache[name] = splitOnDot(name)[0]); } function retrieveFromCurrentState(key) { return function () { return get(this.currentState, key); }; } /* `InternalModel` is the Model class that we use internally inside Ember Data to represent models. Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class. We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as a performance optimization. `InternalModel` should never be exposed to application code. At the boundaries of the system, in places like `find`, `push`, etc. we convert between Models and InternalModels. We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model` if they are needed. @private @class InternalModel */ function InternalModel(type, id, store, _, data) { this.type = type; this.id = id; this.store = store; this._data = data || new _emberDataPrivateSystemEmptyObject.default(); this.modelName = type.modelName; this.dataHasInitialized = false; //Look into making this lazy this._deferredTriggers = []; this._attributes = new _emberDataPrivateSystemEmptyObject.default(); this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); this._relationships = new _emberDataPrivateSystemRelationshipsStateCreate.default(this); this._recordArrays = undefined; this.currentState = _emberDataPrivateSystemModelStates.default.empty; this.recordReference = new _emberDataPrivateSystemReferences.RecordReference(store, this); this.references = {}; this.isReloading = false; this.isError = false; this.error = null; this.__ember_meta__ = null; this[_ember.default.GUID_KEY] = _ember.default.guidFor(this); /* implicit relationships are relationship which have not been declared but the inverse side exists on another record somewhere For example if there was ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr() }) ``` but there is also ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr(), comments: DS.hasMany('comment') }) ``` would have a implicit post relationship in order to be do things like remove ourselves from the post when we are deleted */ this._implicitRelationships = new _emberDataPrivateSystemEmptyObject.default(); } InternalModel.prototype = { isEmpty: retrieveFromCurrentState('isEmpty'), isLoading: retrieveFromCurrentState('isLoading'), isLoaded: retrieveFromCurrentState('isLoaded'), hasDirtyAttributes: retrieveFromCurrentState('hasDirtyAttributes'), isSaving: retrieveFromCurrentState('isSaving'), isDeleted: retrieveFromCurrentState('isDeleted'), isNew: retrieveFromCurrentState('isNew'), isValid: retrieveFromCurrentState('isValid'), dirtyType: retrieveFromCurrentState('dirtyType'), constructor: InternalModel, materializeRecord: function () { (0, _emberDataPrivateDebug.assert)("Materialized " + this.modelName + " record with id:" + this.id + "more than once", this.record === null || this.record === undefined); // lookupFactory should really return an object that creates // instances with the injections applied var createOptions = { store: this.store, _internalModel: this, id: this.id, currentState: get(this, 'currentState'), isError: this.isError, adapterError: this.error }; if (_ember.default.setOwner) { // ensure that `Ember.getOwner(this)` works inside a model instance _ember.default.setOwner(createOptions, (0, _emberDataPrivateUtils.getOwner)(this.store)); } else { createOptions.container = this.store.container; } this.record = this.type._create(createOptions); this._triggerDeferredTriggers(); }, recordObjectWillDestroy: function () { this.record = null; }, deleteRecord: function () { this.send('deleteRecord'); }, save: function (options) { var promiseLabel = "DS: Model#save " + this; var resolver = _ember.default.RSVP.defer(promiseLabel); this.store.scheduleSave(this, resolver, options); return resolver.promise; }, startedReloading: function () { this.isReloading = true; if (this.record) { set(this.record, 'isReloading', true); } }, finishedReloading: function () { this.isReloading = false; if (this.record) { set(this.record, 'isReloading', false); } }, reload: function () { this.startedReloading(); var record = this; var promiseLabel = "DS: Model#reload of " + this; return new Promise(function (resolve) { record.send('reloadRecord', resolve); }, promiseLabel).then(function () { record.didCleanError(); return record; }, function (error) { record.didError(error); throw error; }, "DS: Model#reload complete, update flags").finally(function () { record.finishedReloading(); record.updateRecordArrays(); }); }, getRecord: function () { if (!this.record) { this.materializeRecord(); } return this.record; }, unloadRecord: function () { this.send('unloadRecord'); }, eachRelationship: function (callback, binding) { return this.type.eachRelationship(callback, binding); }, eachAttribute: function (callback, binding) { return this.type.eachAttribute(callback, binding); }, inverseFor: function (key) { return this.type.inverseFor(key); }, setupData: function (data) { var changedKeys = this._changedKeys(data.attributes); assign(this._data, data.attributes); this.pushedData(); if (this.record) { this.record._notifyProperties(changedKeys); } this.didInitalizeData(); }, becameReady: function () { _ember.default.run.schedule('actions', this.store.recordArrayManager, this.store.recordArrayManager.recordWasLoaded, this); }, didInitalizeData: function () { if (!this.dataHasInitialized) { this.becameReady(); this.dataHasInitialized = true; } }, destroy: function () { if (this.record) { return this.record.destroy(); } }, /* @method createSnapshot @private */ createSnapshot: function (options) { return new _emberDataPrivateSystemSnapshot.default(this, options); }, /* @method loadingData @private @param {Promise} promise */ loadingData: function (promise) { this.send('loadingData', promise); }, /* @method loadedData @private */ loadedData: function () { this.send('loadedData'); this.didInitalizeData(); }, /* @method notFound @private */ notFound: function () { this.send('notFound'); }, /* @method pushedData @private */ pushedData: function () { this.send('pushedData'); }, flushChangedAttributes: function () { this._inFlightAttributes = this._attributes; this._attributes = new _emberDataPrivateSystemEmptyObject.default(); }, hasChangedAttributes: function () { return Object.keys(this._attributes).length > 0; }, /* Checks if the attributes which are considered as changed are still different to the state which is acknowledged by the server. This method is needed when data for the internal model is pushed and the pushed data might acknowledge dirty attributes as confirmed. @method updateChangedAttributes @private */ updateChangedAttributes: function () { var changedAttributes = this.changedAttributes(); var changedAttributeNames = Object.keys(changedAttributes); for (var i = 0, _length = changedAttributeNames.length; i < _length; i++) { var attribute = changedAttributeNames[i]; var _changedAttributes$attribute = _slicedToArray(changedAttributes[attribute], 2); var oldData = _changedAttributes$attribute[0]; var newData = _changedAttributes$attribute[1]; if (oldData === newData) { delete this._attributes[attribute]; } } }, /* Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. @method changedAttributes @private */ changedAttributes: function () { var oldData = this._data; var currentData = this._attributes; var inFlightData = this._inFlightAttributes; var newData = assign(copy(inFlightData), currentData); var diffData = new _emberDataPrivateSystemEmptyObject.default(); var newDataKeys = Object.keys(newData); for (var i = 0, _length2 = newDataKeys.length; i < _length2; i++) { var key = newDataKeys[i]; diffData[key] = [oldData[key], newData[key]]; } return diffData; }, /* @method adapterWillCommit @private */ adapterWillCommit: function () { this.send('willCommit'); }, /* @method adapterDidDirty @private */ adapterDidDirty: function () { this.send('becomeDirty'); this.updateRecordArraysLater(); }, /* @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); }, notifyHasManyAdded: function (key, record, idx) { if (this.record) { this.record.notifyHasManyAdded(key, record, idx); } }, notifyHasManyRemoved: function (key, record, idx) { if (this.record) { this.record.notifyHasManyRemoved(key, record, idx); } }, notifyBelongsToChanged: function (key, record) { if (this.record) { this.record.notifyBelongsToChanged(key, record); } }, notifyPropertyChange: function (key) { if (this.record) { this.record.notifyPropertyChange(key); } }, rollbackAttributes: function () { var dirtyKeys = Object.keys(this._attributes); this._attributes = new _emberDataPrivateSystemEmptyObject.default(); if (get(this, 'isError')) { this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); this.didCleanError(); } //Eventually rollback will always work for relationships //For now we support it only out of deleted state, because we //have an explicit way of knowing when the server acked the relationship change if (this.isDeleted()) { //TODO: Should probably move this to the state machine somehow this.becameReady(); } if (this.isNew()) { this.clearRelationships(); } if (this.isValid()) { this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); } this.send('rolledBack'); this.record._notifyProperties(dirtyKeys); }, /* @method transitionTo @private @param {String} name */ transitionTo: function (name) { // POSSIBLE TODO: Remove this code and replace with // always having direct reference to state objects var pivotName = extractPivotName(name); var currentState = get(this, 'currentState'); var state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = splitOnDot(name); var setups = []; var enters = []; var 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); //TODO Consider whether this is the best approach for keeping these two in sync if (this.record) { set(this.record, '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.default.inspect(context) + "."; } throw new _ember.default.Error(errorMessage); }, triggerLater: function () { var length = arguments.length; var args = new Array(length); for (var i = 0; i < length; i++) { args[i] = arguments[i]; } if (this._deferredTriggers.push(args) !== 1) { return; } _ember.default.run.scheduleOnce('actions', this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function () { //TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record, //but for now, we queue up all the events triggered before the record was materialized, and flush //them once we have the record if (!this.record) { return; } for (var i = 0, l = this._deferredTriggers.length; i < l; i++) { this.record.trigger.apply(this.record, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; }, /* @method clearRelationships @private */ clearRelationships: function () { var _this = this; this.eachRelationship(function (name, relationship) { if (_this._relationships.has(name)) { var rel = _this._relationships.get(name); rel.clear(); rel.destroy(); } }); Object.keys(this._implicitRelationships).forEach(function (key) { _this._implicitRelationships[key].clear(); _this._implicitRelationships[key].destroy(); }); }, /* When a find request is triggered on the store, the user can optionally pass in attributes and relationships to be preloaded. These are meant to behave as if they came back from the server, except the user obtained them out of band and is informing the store of their existence. The most common use case is for supporting client side nested URLs, such as `/posts/1/comments/2` so the user can do `store.findRecord('comment', 2, { preload: { post: 1 } })` without having to fetch the post. Preloaded data can be attributes and relationships passed in either as IDs or as actual models. @method _preloadData @private @param {Object} preload */ _preloadData: function (preload) { var _this2 = this; //TODO(Igor) consider the polymorphic case Object.keys(preload).forEach(function (key) { var preloadValue = get(preload, key); var relationshipMeta = _this2.type.metaForProperty(key); if (relationshipMeta.isRelationship) { _this2._preloadRelationship(key, preloadValue); } else { _this2._data[key] = preloadValue; } }); }, _preloadRelationship: function (key, preloadValue) { var relationshipMeta = this.type.metaForProperty(key); var type = relationshipMeta.type; if (relationshipMeta.kind === 'hasMany') { this._preloadHasMany(key, preloadValue, type); } else { this._preloadBelongsTo(key, preloadValue, type); } }, _preloadHasMany: function (key, preloadValue, type) { (0, _emberDataPrivateDebug.assert)("You need to pass in an array to set a hasMany property on a record", Array.isArray(preloadValue)); var recordsToSet = new Array(preloadValue.length); for (var i = 0; i < preloadValue.length; i++) { var recordToPush = preloadValue[i]; recordsToSet[i] = this._convertStringOrNumberIntoInternalModel(recordToPush, type); } //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).updateRecordsFromAdapter(recordsToSet); }, _preloadBelongsTo: function (key, preloadValue, type) { var recordToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, type); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).setRecord(recordToSet); }, _convertStringOrNumberIntoInternalModel: function (value, type) { if (typeof value === 'string' || typeof value === 'number') { return this.store._internalModelForId(type, value); } if (value._internalModel) { return value._internalModel; } return value; }, /* @method updateRecordArrays @private */ updateRecordArrays: function () { this._updatingRecordArraysLater = false; this.store.dataWasUpdated(this.type, this); }, setId: function (id) { (0, _emberDataPrivateDebug.assert)('A record\'s id cannot be changed once it is in the loaded state', this.id === null || this.id === id || this.isNew()); this.id = id; if (this.record.get('id') !== id) { this.record.set('id', id); } }, didError: function (error) { this.error = error; this.isError = true; if (this.record) { this.record.setProperties({ isError: true, adapterError: error }); } }, didCleanError: function () { this.error = null; this.isError = false; if (this.record) { this.record.setProperties({ isError: false, adapterError: null }); } }, /* 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) { if (data) { data = data.attributes; } this.didCleanError(); var changedKeys = this._changedKeys(data); assign(this._data, this._inFlightAttributes); if (data) { assign(this._data, data); } this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.record._notifyProperties(changedKeys); }, /* @method updateRecordArraysLater @private */ updateRecordArraysLater: function () { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; _ember.default.run.schedule('actions', this, this.updateRecordArrays); }, addErrorMessageToAttribute: function (attribute, message) { var record = this.getRecord(); get(record, 'errors')._add(attribute, message); }, removeErrorMessageFromAttribute: function (attribute) { var record = this.getRecord(); get(record, 'errors')._remove(attribute); }, clearErrorMessages: function () { var record = this.getRecord(); get(record, 'errors')._clear(); }, hasErrors: function () { var record = this.getRecord(); var errors = get(record, 'errors'); return !_ember.default.isEmpty(errors); }, // FOR USE DURING COMMIT PROCESS /* @method adapterDidInvalidate @private */ adapterDidInvalidate: function (errors) { var attribute; for (attribute in errors) { if (errors.hasOwnProperty(attribute)) { this.addErrorMessageToAttribute(attribute, errors[attribute]); } } this.send('becameInvalid'); this._saveWasRejected(); }, /* @method adapterDidError @private */ adapterDidError: function (error) { this.send('becameError'); this.didError(error); this._saveWasRejected(); }, _saveWasRejected: function () { var keys = Object.keys(this._inFlightAttributes); for (var i = 0; i < keys.length; i++) { if (this._attributes[keys[i]] === undefined) { this._attributes[keys[i]] = this._inFlightAttributes[keys[i]]; } } this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); }, /* Ember Data has 3 buckets for storing the value of an attribute on an internalModel. `_data` holds all of the attributes that have been acknowledged by a backend via the adapter. When rollbackAttributes is called on a model all attributes will revert to the record's state in `_data`. `_attributes` holds any change the user has made to an attribute that has not been acknowledged by the adapter. Any values in `_attributes` are have priority over values in `_data`. `_inFlightAttributes`. When a record is being synced with the backend the values in `_attributes` are copied to `_inFlightAttributes`. This way if the backend acknowledges the save but does not return the new state Ember Data can copy the values from `_inFlightAttributes` to `_data`. Without having to worry about changes made to `_attributes` while the save was happenign. Changed keys builds a list of all of the values that may have been changed by the backend after a successful save. It does this by iterating over each key, value pair in the payload returned from the server after a save. If the `key` is found in `_attributes` then the user has a local changed to the attribute that has not been synced with the server and the key is not included in the list of changed keys. If the value, for a key differs from the value in what Ember Data believes to be the truth about the backend state (A merger of the `_data` and `_inFlightAttributes` objects where `_inFlightAttributes` has priority) then that means the backend has updated the value and the key is added to the list of changed keys. @method _changedKeys @private */ _changedKeys: function (updates) { var changedKeys = []; if (updates) { var original, i, value, key; var keys = Object.keys(updates); var length = keys.length; original = assign(new _emberDataPrivateSystemEmptyObject.default(), this._data); original = assign(original, this._inFlightAttributes); for (i = 0; i < length; i++) { key = keys[i]; value = updates[key]; // A value in _attributes means the user has a local change to // this attributes. We never override this value when merging // updates from the backend so we should not sent a change // notification if the server value differs from the original. if (this._attributes[key] !== undefined) { continue; } if (!_ember.default.isEqual(original[key], value)) { changedKeys.push(key); } } } return changedKeys; }, toString: function () { if (this.record) { return this.record.toString(); } else { return "<" + this.modelName + ":" + this.id + ">"; } }, referenceFor: function (type, name) { var _this3 = this; var reference = this.references[name]; if (!reference) { var relationship = this._relationships.get(name); (0, _emberDataPrivateDebug.runInDebug)(function () { var modelName = _this3.modelName; (0, _emberDataPrivateDebug.assert)("There is no " + type + " relationship named '" + name + "' on a model of type '" + modelName + "'", relationship); var actualRelationshipKind = relationship.relationshipMeta.kind; (0, _emberDataPrivateDebug.assert)("You tried to get the '" + name + "' relationship on a '" + modelName + "' via record." + type + "('" + name + "'), but the relationship is of type '" + actualRelationshipKind + "'. Use record." + actualRelationshipKind + "('" + name + "') instead.", actualRelationshipKind === type); }); if (type === "belongsTo") { reference = new _emberDataPrivateSystemReferences.BelongsToReference(this.store, this, relationship); } else if (type === "hasMany") { reference = new _emberDataPrivateSystemReferences.HasManyReference(this.store, this, relationship); } this.references[name] = reference; } return reference; } }; if ((0, _emberDataPrivateFeatures.default)('ds-reset-attribute')) { /* Returns the latest truth for an attribute - the canonical value, or the in-flight value. @method lastAcknowledgedValue @private */ InternalModel.prototype.lastAcknowledgedValue = function lastAcknowledgedValue(key) { if (key in this._inFlightAttributes) { return this._inFlightAttributes[key]; } else { return this._data[key]; } }; } }); define("ember-data/-private/system/model/model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/model/errors", "ember-data/-private/system/debug/debug-info", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many", "ember-data/-private/system/relationships/ext", "ember-data/-private/system/model/attr", "ember-data/-private/features"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemModelErrors, _emberDataPrivateSystemDebugDebugInfo, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany, _emberDataPrivateSystemRelationshipsExt, _emberDataPrivateSystemModelAttr, _emberDataPrivateFeatures) { /** @module ember-data */ var get = _ember.default.get; function intersection(array1, array2) { var result = []; array1.forEach(function (element) { if (array2.indexOf(element) >= 0) { result.push(element); } }); return result; } var RESERVED_MODEL_PROPS = ['currentState', 'data', 'store']; var retrieveFromCurrentState = _ember.default.computed('currentState', function (key) { return get(this._internalModel.currentState, key); }).readOnly(); /** The model class that all Ember Data records descend from. This is the public API of Ember Data models. If you are using Ember Data in your application, this is the class you should use. If you are working on Ember Data internals, you most likely want to be dealing with `InternalModel` @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ var Model = _ember.default.Object.extend(_ember.default.Evented, { _internalModel: null, store: null, /** 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.findRecord('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('hasDirtyAttributes'); // true store.findRecord('model', 1).then(function(model) { model.get('hasDirtyAttributes'); // false model.set('foo', 'some value'); model.get('hasDirtyAttributes'); // true }); ``` @since 1.13.0 @property hasDirtyAttributes @type {Boolean} @readOnly */ hasDirtyAttributes: _ember.default.computed('currentState.isDirty', function () { return this.get('currentState.isDirty'); }), /** 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 `hasDirtyAttributes` 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 `hasDirtyAttributes` 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('hasDirtyAttributes'); // 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('hasDirtyAttributes'); // 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, /** 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.findRecord('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash contains keys corresponding to the invalid property names and values which are arrays of Javascript objects with two keys: - `message` A string containing the error message from the backend - `attribute` The name of the property associated with this error message ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().catch(function() { record.get('errors').get('foo'); // [{message: 'foo should be a number.', attribute: 'foo'}] }); ``` The `errors` property us useful for displaying error messages to the user. ```handlebars <label>Username: {{input value=username}} </label> {{#each model.errors.username as |error|}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each model.errors.email as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` You can also access the special `messages` property on the error object to get an array of all the error strings. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @property errors @type {DS.Errors} */ errors: _ember.default.computed(function () { var errors = _emberDataPrivateSystemModelErrors.default.create(); errors._registerHandlers(this._internalModel, function () { this.send('becameInvalid'); }, function () { this.send('becameValid'); }); return errors; }).readOnly(), /** This property holds the `DS.AdapterError` object with which last adapter operation was rejected. @property adapterError @type {DS.AdapterError} */ adapterError: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function (options) { return this.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) { // container is for lazy transform lookups var serializer = this.store.serializerFor('-default'); var snapshot = this._internalModel.createSnapshot(); return serializer.serialize(snapshot, options); }, /** Fired when the record is ready to be interacted with, that is either loaded from the server or created locally. @event ready */ ready: _ember.default.K, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: _ember.default.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: _ember.default.K, /** Fired when a new record is commited to the server. @event didCreate */ didCreate: _ember.default.K, /** Fired when the record is deleted. @event didDelete */ didDelete: _ember.default.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: _ember.default.K, /** Fired when the record enters the error state. @event becameError */ becameError: _ember.default.K, /** Fired when the record is rolled back. @event rolledBack */ rolledBack: _ember.default.K, //TODO Do we want to deprecate these? /** @method send @private @param {String} name @param {Object} context */ send: function (name, context) { return this._internalModel.send(name, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function (name) { return this._internalModel.transitionTo(name); }, /** 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 `rollbackAttributes()` after a delete it was made. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { softDelete: function() { this.controller.get('model').deleteRecord(); }, confirm: function() { this.controller.get('model').save(); }, undo: function() { this.controller.get('model').rollbackAttributes(); } } }); ``` @method deleteRecord */ deleteRecord: function () { this._internalModel.deleteRecord(); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; controller.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```js record.destroyRecord({ adapterOptions: { subscribe: false } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ deleteRecord: function(store, type, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` @method destroyRecord @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function (options) { this.deleteRecord(); return this.save(options); }, /** @method unloadRecord @private */ unloadRecord: function () { if (this.isDestroyed) { return; } this._internalModel.unloadRecord(); }, /** @method _notifyProperties @private */ _notifyProperties: function (keys) { _ember.default.beginPropertyChanges(); var key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; this.notifyPropertyChange(key); } _ember.default.endPropertyChanges(); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. The array represents the diff of the canonical state with the local state of the model. Note: if the model is created locally, the canonical state is empty since the adapter hasn't acknowledged the attributes yet: Example ```app/models/mascot.js import DS from 'ember-data'; export default DS.Model.extend({ name: attr('string'), isAdmin: attr('boolean', { defaultValue: false }) }); ``` ```javascript var mascot = store.createRecord('mascot'); mascot.changedAttributes(); // {} mascot.set('name', 'Tomster'); mascot.changedAttributes(); // { name: [undefined, 'Tomster'] } mascot.set('isAdmin', true); mascot.changedAttributes(); // { isAdmin: [undefined, true], name: [undefined, 'Tomster'] } mascot.save().then(function() { mascot.changedAttributes(); // {} mascot.set('isAdmin', false); mascot.changedAttributes(); // { isAdmin: [true, false] } }); ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function () { return this._internalModel.changedAttributes(); }, //TODO discuss with tomhuda about events/hooks //Bring back as hooks? /** @method adapterWillCommit @private adapterWillCommit: function() { this.send('willCommit'); }, /** @method adapterDidDirty @private adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, */ /** If the model `hasDirtyAttributes` this function will discard any unsaved changes. If the model `isNew` it will be removed from the store. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollbackAttributes(); record.get('name'); // 'Untitled Document' ``` @since 1.13.0 @method rollbackAttributes */ rollbackAttributes: function () { this._internalModel.rollbackAttributes(); }, /* @method _createSnapshot @private */ _createSnapshot: function () { return this._internalModel.createSnapshot(); }, toStringExtension: function () { return get(this, 'id'); }, /** Save the record and persist any changes to the record to an external source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function() { // Success callback }, function() { // Error callback }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```js record.save({ adapterOptions: { subscribe: false } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ updateRecord: function(store, type, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` @method save @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function (options) { var _this = this; return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ promise: this._internalModel.save(options).then(function () { return _this; }) }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading. Example ```app/routes/model/view.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { reload: function() { this.controller.get('model').reload().then(function(model) { // do something with the reloaded model }); } } }); ``` @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 () { var _this2 = this; return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ promise: this._internalModel.reload().then(function () { return _this2; }) }); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param {String} name */ trigger: function (name) { var length = arguments.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } _ember.default.tryInvoke(this, name, args); this._super.apply(this, arguments); }, willDestroy: function () { //TODO Move! this._super.apply(this, arguments); this._internalModel.clearRelationships(); this._internalModel.recordObjectWillDestroy(); //TODO should we set internalModel to null here? }, // This is a temporary solution until we refactor DS.Model to not // rely on the data property. willMergeMixin: function (props) { var constructor = this.constructor; (0, _emberDataPrivateDebug.assert)('`' + intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0]); (0, _emberDataPrivateDebug.assert)("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + constructor.toString(), Object.keys(props).indexOf('id') === -1); }, attr: function () { (0, _emberDataPrivateDebug.assert)("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); }, /** Get the reference for the specified belongsTo relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ type: 'blog', id: 1, relationships: { user: { type: 'user', id: 1 } } }); var userRef = blog.belongsTo('user'); // check if the user relationship is loaded var isLoaded = userRef.value() !== null; // get the record of the reference (null if not yet available) var user = userRef.value(); // get the identifier of the reference if (userRef.remoteType() === "id") { var id = userRef.id(); } else if (userRef.remoteType() === "link") { var link = userRef.link(); } // load user (via store.findRecord or store.findBelongsTo) userRef.load().then(...) // or trigger a reload userRef.reload().then(...) // provide data for reference userRef.push({ type: 'user', id: 1, attributes: { username: "@user" } }).then(function(user) { userRef.value() === user; }); ``` @method belongsTo @param {String} name of the relationship @since 2.5.0 @return {BelongsToReference} reference for this relationship */ belongsTo: function (name) { return this._internalModel.referenceFor('belongsTo', name); }, /** Get the reference for the specified hasMany relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); var blog = store.push({ type: 'blog', id: 1, relationships: { comments: { data: [ { type: 'comment', id: 1 }, { type: 'comment', id: 2 } ] } } }); var commentsRef = blog.hasMany('comments'); // check if the comments are loaded already var isLoaded = commentsRef.value() !== null; // get the records of the reference (null if not yet available) var comments = commentsRef.value(); // get the identifier of the reference if (commentsRef.remoteType() === "ids") { var ids = commentsRef.ids(); } else if (commentsRef.remoteType() === "link") { var link = commentsRef.link(); } // load comments (via store.findMany or store.findHasMany) commentsRef.load().then(...) // or trigger a reload commentsRef.reload().then(...) // provide data for reference commentsRef.push([{ type: 'comment', id: 1 }, { type: 'comment', id: 2 }]).then(function(comments) { commentsRef.value() === comments; }); ``` @method hasMany @param {String} name of the relationship @since 2.5.0 @return {HasManyReference} reference for this relationship */ hasMany: function (name) { return this._internalModel.referenceFor('hasMany', name); }, setId: _ember.default.observer('id', function () { this._internalModel.setId(this.get('id')); }) }); /** @property data @private @type {Object} */ Object.defineProperty(Model.prototype, 'data', { get: function () { return this._internalModel._data; } }); 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.default.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); }, /** Represents the model's class name as a string. This can be used to look up the model through DS.Store's modelFor method. `modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string. For example: ```javascript store.modelFor('post').modelName; // 'post' store.modelFor('blog-post').modelName; // 'blog-post' ``` The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload keys to underscore (instead of dasherized), you might use the following code: ```javascript export default var PostSerializer = DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.underscore(modelName); } }); ``` @property modelName @type String @readonly @static */ modelName: null }); // if `Ember.setOwner` is defined, accessing `this.container` is // deprecated (but functional). In "standard" Ember usage, this // deprecation is actually created via an `.extend` of the factory // inside the container itself, but that only happens on models // with MODEL_FACTORY_INJECTIONS enabled :( if (_ember.default.setOwner) { Object.defineProperty(Model.prototype, 'container', { configurable: true, enumerable: false, get: function () { (0, _emberDataPrivateDebug.deprecate)('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.', false, { id: 'ember-application.injected-container', until: '3.0.0' }); return this.store.container; } }); } if ((0, _emberDataPrivateFeatures.default)('ds-reset-attribute')) { Model.reopen({ /** Discards any unsaved changes to the given attribute. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.resetAttribute('name'); record.get('name'); // 'Untitled Document' ``` @method resetAttribute */ resetAttribute: function (attributeName) { if (attributeName in this._internalModel._attributes) { this.set(attributeName, this._internalModel.lastAcknowledgedValue(attributeName)); } } }); } Model.reopenClass(_emberDataPrivateSystemRelationshipsExt.RelationshipsClassMethodsMixin); Model.reopenClass(_emberDataPrivateSystemModelAttr.AttrClassMethodsMixin); exports.default = Model.extend(_emberDataPrivateSystemDebugDebugInfo.default, _emberDataPrivateSystemRelationshipsBelongsTo.BelongsToMixin, _emberDataPrivateSystemRelationshipsExt.DidDefinePropertyMixin, _emberDataPrivateSystemRelationshipsExt.RelationshipsInstanceMethodsMixin, _emberDataPrivateSystemRelationshipsHasMany.HasManyMixin, _emberDataPrivateSystemModelAttr.AttrInstanceMethodsMixin); }); define('ember-data/-private/system/model/states', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { var get = _ember.default.get; /* 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. (This 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 that means 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 didSetProperty(internalModel, context) { if (context.value === context.originalValue) { delete internalModel._attributes[context.name]; internalModel.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { internalModel.send('becomeDirty'); } internalModel.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. // * 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 // sent 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, //TODO(Igor) reloading now triggers a //loadingData event, though it seems fine? loadingData: _ember.default.K, propertyWasReset: function (internalModel, name) { if (!internalModel.hasChangedAttributes()) { internalModel.send('rolledBack'); } }, pushedData: function (internalModel) { internalModel.updateChangedAttributes(); if (!internalModel.hasChangedAttributes()) { internalModel.transitionTo('loaded.saved'); } }, becomeDirty: _ember.default.K, willCommit: function (internalModel) { internalModel.transitionTo('inFlight'); }, reloadRecord: function (internalModel, resolve) { resolve(internalModel.store.reloadRecord(internalModel)); }, rolledBack: function (internalModel) { internalModel.transitionTo('loaded.saved'); }, becameInvalid: function (internalModel) { internalModel.transitionTo('invalid'); }, rollback: function (internalModel) { internalModel.rollbackAttributes(); internalModel.triggerLater('ready'); } }, // 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.default.K, pushedData: _ember.default.K, unloadRecord: assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: _ember.default.K, didCommit: function (internalModel) { var dirtyType = get(this, 'dirtyType'); internalModel.transitionTo('saved'); internalModel.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function (internalModel) { internalModel.transitionTo('invalid'); internalModel.send('invokeLifecycleCallbacks'); }, becameError: function (internalModel) { internalModel.transitionTo('uncommitted'); internalModel.triggerLater('becameError', internalModel); } }, // 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 (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }, didSetProperty: function (internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); didSetProperty(internalModel, context); if (!internalModel.hasErrors()) { this.becameValid(internalModel); } }, becameInvalid: _ember.default.K, becomeDirty: _ember.default.K, pushedData: _ember.default.K, willCommit: function (internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('inFlight'); }, rolledBack: function (internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); }, becameValid: function (internalModel) { internalModel.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function (internalModel) { internalModel.triggerLater('becameInvalid', internalModel); } } }; // 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 = {}; var 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.invalid.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; createdState.uncommitted.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); function createdStateDeleteRecord(internalModel) { internalModel.transitionTo('deleted.saved'); internalModel.send('invokeLifecycleCallbacks'); } createdState.uncommitted.deleteRecord = createdStateDeleteRecord; createdState.invalid.deleteRecord = createdStateDeleteRecord; createdState.uncommitted.rollback = function (internalModel) { DirtyState.uncommitted.rollback.apply(this, arguments); internalModel.transitionTo('deleted.saved'); }; createdState.uncommitted.pushedData = function (internalModel) { internalModel.transitionTo('loaded.updated.uncommitted'); internalModel.triggerLater('didLoad'); }; createdState.uncommitted.propertyWasReset = _ember.default.K; function assertAgainstUnloadRecord(internalModel) { (0, _emberDataPrivateDebug.assert)("You can only unload a record which is not inFlight. `" + internalModel + "`", false); } updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord; updatedState.uncommitted.deleteRecord = function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }; 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.default.K, unloadRecord: function (internalModel) { // clear relationships before moving to deleted state // otherwise it fails internalModel.clearRelationships(); internalModel.transitionTo('deleted.saved'); }, propertyWasReset: _ember.default.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 (internalModel, promise) { internalModel._loadingPromise = promise; internalModel.transitionTo('loading'); }, loadedData: function (internalModel) { internalModel.transitionTo('loaded.created.uncommitted'); internalModel.triggerLater('ready'); }, pushedData: function (internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('didLoad'); internalModel.triggerLater('ready'); } }, // 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 (internalModel) { internalModel._loadingPromise = null; }, // EVENTS pushedData: function (internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('didLoad'); internalModel.triggerLater('ready'); //TODO this seems out of place here internalModel.didCleanError(); }, becameError: function (internalModel) { internalModel.triggerLater('becameError', internalModel); }, notFound: function (internalModel) { internalModel.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, //TODO(Igor) Reloading now triggers a loadingData event, //but it should be ok? loadingData: _ember.default.K, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function (internalModel) { if (internalModel.hasChangedAttributes()) { internalModel.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: _ember.default.K, becomeDirty: function (internalModel) { internalModel.transitionTo('updated.uncommitted'); }, willCommit: function (internalModel) { internalModel.transitionTo('updated.inFlight'); }, reloadRecord: function (internalModel, resolve) { resolve(internalModel.store.reloadRecord(internalModel)); }, deleteRecord: function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }, unloadRecord: function (internalModel) { // clear relationships before moving to deleted state // otherwise it fails internalModel.clearRelationships(); internalModel.transitionTo('deleted.saved'); }, didCommit: function (internalModel) { internalModel.send('invokeLifecycleCallbacks', get(internalModel, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: _ember.default.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 (internalModel) { internalModel.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 (internalModel) { internalModel.transitionTo('inFlight'); }, rollback: function (internalModel) { internalModel.rollbackAttributes(); internalModel.triggerLater('ready'); }, pushedData: _ember.default.K, becomeDirty: _ember.default.K, deleteRecord: _ember.default.K, rolledBack: function (internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); } }, // 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.default.K, didCommit: function (internalModel) { internalModel.transitionTo('saved'); internalModel.send('invokeLifecycleCallbacks'); }, becameError: function (internalModel) { internalModel.transitionTo('uncommitted'); internalModel.triggerLater('becameError', internalModel); }, becameInvalid: function (internalModel) { internalModel.transitionTo('invalid'); internalModel.triggerLater('becameInvalid', internalModel); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function (internalModel) { internalModel.clearRelationships(); var store = internalModel.store; store._dematerializeRecord(internalModel); }, invokeLifecycleCallbacks: function (internalModel) { internalModel.triggerLater('didDelete', internalModel); internalModel.triggerLater('didCommit', internalModel); }, willCommit: _ember.default.K, didCommit: _ember.default.K }, invalid: { isValid: false, didSetProperty: function (internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); didSetProperty(internalModel, context); if (!internalModel.hasErrors()) { this.becameValid(internalModel); } }, becameInvalid: _ember.default.K, becomeDirty: _ember.default.K, deleteRecord: _ember.default.K, willCommit: _ember.default.K, rolledBack: function (internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); }, becameValid: function (internalModel) { internalModel.transitionTo('uncommitted'); } } }, invokeLifecycleCallbacks: function (internalModel, dirtyType) { if (dirtyType === 'created') { internalModel.triggerLater('didCreate', internalModel); } else { internalModel.triggerLater('didUpdate', internalModel); } internalModel.triggerLater('didCommit', internalModel); } }; function wireState(object, parent, name) { // TODO: Use Object.create and copy instead object = mixin(parent ? Object.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; }); /** @module ember-data */ define('ember-data/-private/system/normalize-link', ['exports'], function (exports) { exports.default = _normalizeLink; /* This method normalizes a link to an "links object". If the passed link is already an object it's returned without any modifications. See http://jsonapi.org/format/#document-links for more information. @method _normalizeLink @private @param {String} link @return {Object|null} @for DS */ function _normalizeLink(link) { switch (typeof link) { case 'object': return link; case 'string': return { href: link }; } return null; } }); define('ember-data/-private/system/normalize-model-name', ['exports', 'ember'], function (exports, _ember) { exports.default = normalizeModelName; // All modelNames are dasherized internally. Changing this function may // require changes to other normalization hooks (such as typeForRoot). /** This method normalizes a modelName into the format Ember Data uses internally. @method normalizeModelName @public @param {String} modelName @return {String} normalizedModelName @for DS */ function normalizeModelName(modelName) { return _ember.default.String.dasherize(modelName); } }); define('ember-data/-private/system/ordered-set', ['exports', 'ember'], function (exports, _ember) { exports.default = OrderedSet; var EmberOrderedSet = _ember.default.OrderedSet; var guidFor = _ember.default.guidFor; function OrderedSet() { this._super$constructor(); } OrderedSet.create = function () { var Constructor = this; return new Constructor(); }; OrderedSet.prototype = Object.create(EmberOrderedSet.prototype); OrderedSet.prototype.constructor = OrderedSet; OrderedSet.prototype._super$constructor = EmberOrderedSet; OrderedSet.prototype.addWithIndex = function (obj, idx) { var guid = guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { return; } presenceSet[guid] = true; if (idx === undefined || idx === null) { list.push(obj); } else { list.splice(idx, 0, obj); } this.size += 1; return this; }; }); define('ember-data/-private/system/promise-proxies', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { var Promise = _ember.default.RSVP.Promise; var get = _ember.default.get; /** 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 */ var PromiseArray = _ember.default.ArrayProxy.extend(_ember.default.PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved, then 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 */ var PromiseObject = _ember.default.ObjectProxy.extend(_ember.default.PromiseProxyMixin); var promiseObject = function (promise, label) { return PromiseObject.create({ promise: Promise.resolve(promise, label) }); }; var promiseArray = function (promise, label) { return PromiseArray.create({ promise: Promise.resolve(promise, label) }); }; /** A PromiseManyArray is a PromiseArray that also proxies certain method calls to the underlying manyArray. Right now we proxy: * `reload()` * `createRecord()` * `on()` * `one()` * `trigger()` * `off()` * `has()` @class PromiseManyArray @namespace DS @extends Ember.ArrayProxy */ function proxyToContent(method) { return function () { var content = get(this, 'content'); return content[method].apply(content, arguments); }; } var PromiseManyArray = PromiseArray.extend({ reload: function () { //I don't think this should ever happen right now, but worth guarding if we refactor the async relationships (0, _emberDataPrivateDebug.assert)('You are trying to reload an async manyArray before it has been created', get(this, 'content')); return PromiseManyArray.create({ promise: get(this, 'content').reload() }); }, createRecord: proxyToContent('createRecord'), on: proxyToContent('on'), one: proxyToContent('one'), trigger: proxyToContent('trigger'), off: proxyToContent('off'), has: proxyToContent('has') }); var promiseManyArray = function (promise, label) { return PromiseManyArray.create({ promise: Promise.resolve(promise, label) }); }; exports.PromiseArray = PromiseArray; exports.PromiseObject = PromiseObject; exports.PromiseManyArray = PromiseManyArray; exports.promiseArray = promiseArray; exports.promiseObject = promiseObject; exports.promiseManyArray = promiseManyArray; }); define("ember-data/-private/system/record-array-manager", ["exports", "ember", "ember-data/-private/system/record-arrays", "ember-data/-private/system/ordered-set"], function (exports, _ember, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemOrderedSet) { var MapWithDefault = _ember.default.MapWithDefault; var get = _ember.default.get; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ exports.default = _ember.default.Object.extend({ init: function () { var _this = this; this.filteredRecordArrays = MapWithDefault.create({ defaultValue: function () { return []; } }); this.liveRecordArrays = MapWithDefault.create({ defaultValue: function (typeClass) { return _this.createRecordArray(typeClass); } }); this.changedRecords = []; this._adapterPopulatedRecordArrays = []; }, recordDidChange: function (record) { if (this.changedRecords.push(record) !== 1) { return; } _ember.default.run.schedule('actions', this, this.updateRecordArrays); }, recordArraysForRecord: function (record) { record._recordArrays = record._recordArrays || _emberDataPrivateSystemOrderedSet.default.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 */ updateRecordArrays: function () { var _this2 = this; this.changedRecords.forEach(function (internalModel) { if (get(internalModel, 'record.isDestroyed') || get(internalModel, 'record.isDestroying') || get(internalModel, 'currentState.stateName') === 'root.deleted.saved') { _this2._recordWasDeleted(internalModel); } else { _this2._recordWasChanged(internalModel); } }); this.changedRecords.length = 0; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } recordArrays.forEach(function (array) { return array.removeInternalModel(record); }); record._recordArrays = null; }, _recordWasChanged: function (record) { var _this3 = this; var typeClass = record.type; var recordArrays = this.filteredRecordArrays.get(typeClass); var filter; recordArrays.forEach(function (array) { filter = get(array, 'filterFunction'); _this3.updateFilterRecordArray(array, filter, typeClass, record); }); }, //Need to update live arrays on loading recordWasLoaded: function (record) { var _this4 = this; var typeClass = record.type; var recordArrays = this.filteredRecordArrays.get(typeClass); var filter; recordArrays.forEach(function (array) { filter = get(array, 'filterFunction'); _this4.updateFilterRecordArray(array, filter, typeClass, record); }); if (this.liveRecordArrays.has(typeClass)) { var liveRecordArray = this.liveRecordArrays.get(typeClass); this._addRecordToRecordArray(liveRecordArray, record); } }, /** Update an individual filter. @method updateFilterRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {DS.Model} typeClass @param {InternalModel} record */ updateFilterRecordArray: function (array, filter, typeClass, record) { var shouldBeInArray = filter(record.getRecord()); var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { this._addRecordToRecordArray(array, record); } else { recordArrays.delete(array); array.removeInternalModel(record); } }, _addRecordToRecordArray: function (array, record) { var recordArrays = this.recordArraysForRecord(record); if (!recordArrays.has(array)) { array.addInternalModel(record); recordArrays.add(array); } }, populateLiveRecordArray: function (array, modelName) { var typeMap = this.store.typeMapFor(modelName); var records = typeMap.records; var record; for (var i = 0; i < records.length; i++) { record = records[i]; if (!record.isDeleted() && !record.isEmpty()) { this._addRecordToRecordArray(array, 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} array @param {String} modelName @param {Function} filter */ updateFilter: function (array, modelName, filter) { var typeMap = this.store.typeMapFor(modelName); var records = typeMap.records; var record; for (var i = 0; i < records.length; i++) { record = records[i]; if (!record.isDeleted() && !record.isEmpty()) { this.updateFilterRecordArray(array, filter, modelName, record); } } }, /** Get the `DS.RecordArray` for a type, which contains all loaded records of given type. @method liveRecordArrayFor @param {Class} typeClass @return {DS.RecordArray} */ liveRecordArrayFor: function (typeClass) { return this.liveRecordArrays.get(typeClass); }, /** Create a `DS.RecordArray` for a type. @method createRecordArray @param {Class} typeClass @return {DS.RecordArray} */ createRecordArray: function (typeClass) { var array = _emberDataPrivateSystemRecordArrays.RecordArray.create({ type: typeClass, content: _ember.default.A(), store: this.store, isLoaded: true, manager: this }); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {DS.Model} typeClass @param {Function} filter @param {Object} query (optional @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function (typeClass, filter, query) { var array = _emberDataPrivateSystemRecordArrays.FilteredRecordArray.create({ query: query, type: typeClass, content: _ember.default.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, typeClass, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {DS.Model} typeClass @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function (typeClass, query) { var array = _emberDataPrivateSystemRecordArrays.AdapterPopulatedRecordArray.create({ type: typeClass, query: query, content: _ember.default.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 {DS.Model} typeClass @param {Function} filter */ registerFilteredRecordArray: function (array, typeClass, filter) { var recordArrays = this.filteredRecordArrays.get(typeClass); recordArrays.push(array); this.updateFilter(array, typeClass, filter); }, /** Unregister a RecordArray. So manager will not update this array. @method unregisterRecordArray @param {DS.RecordArray} array */ unregisterRecordArray: function (array) { var typeClass = array.type; // unregister filtered record array var recordArrays = this.filteredRecordArrays.get(typeClass); var removedFromFiltered = remove(recordArrays, array); // remove from adapter populated record array var removedFromAdapterPopulated = remove(this._adapterPopulatedRecordArrays, array); if (!removedFromFiltered && !removedFromAdapterPopulated) { // unregister live record array if (this.liveRecordArrays.has(typeClass)) { var liveRecordArrayForType = this.liveRecordArrayFor(typeClass); if (array === liveRecordArrayForType) { this.liveRecordArrays.delete(typeClass); } } } }, willDestroy: function () { this._super.apply(this, arguments); this.filteredRecordArrays.forEach(function (value) { return flatten(value).forEach(destroy); }); this.liveRecordArrays.forEach(destroy); this._adapterPopulatedRecordArrays.forEach(destroy); } }); function destroy(entry) { entry.destroy(); } function flatten(list) { var length = list.length; var result = _ember.default.A(); for (var i = 0; i < length; i++) { result = result.concat(list[i]); } return result; } function remove(array, item) { var index = array.indexOf(item); if (index !== -1) { array.splice(index, 1); return true; } return false; } }); /** @module ember-data */ define("ember-data/-private/system/record-arrays", ["exports", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/record-arrays/filtered-record-array", "ember-data/-private/system/record-arrays/adapter-populated-record-array"], function (exports, _emberDataPrivateSystemRecordArraysRecordArray, _emberDataPrivateSystemRecordArraysFilteredRecordArray, _emberDataPrivateSystemRecordArraysAdapterPopulatedRecordArray) { exports.RecordArray = _emberDataPrivateSystemRecordArraysRecordArray.default; exports.FilteredRecordArray = _emberDataPrivateSystemRecordArraysFilteredRecordArray.default; exports.AdapterPopulatedRecordArray = _emberDataPrivateSystemRecordArraysAdapterPopulatedRecordArray.default; }); /** @module ember-data */ define("ember-data/-private/system/record-arrays/adapter-populated-record-array", ["exports", "ember", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/clone-null", "ember-data/-private/features"], function (exports, _ember, _emberDataPrivateSystemRecordArraysRecordArray, _emberDataPrivateSystemCloneNull, _emberDataPrivateFeatures) { /** @module ember-data */ var get = _ember.default.get; /** 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 */ exports.default = _emberDataPrivateSystemRecordArraysRecordArray.default.extend({ query: null, replace: function () { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, _update: function () { var store = get(this, 'store'); var modelName = get(this, 'type.modelName'); var query = get(this, 'query'); return store._query(modelName, query, this); }, /** @method loadRecords @param {Array} records @param {Object} payload normalized payload @private */ loadRecords: function (records, payload) { var _this = this; //TODO Optimize var internalModels = _ember.default.A(records).mapBy('_internalModel'); this.setProperties({ content: _ember.default.A(internalModels), isLoaded: true, isUpdating: false, meta: (0, _emberDataPrivateSystemCloneNull.default)(payload.meta) }); if (true) { this.set('links', (0, _emberDataPrivateSystemCloneNull.default)(payload.links)); } internalModels.forEach(function (record) { _this.manager.recordArraysForRecord(record).add(_this); }); // TODO: should triggering didLoad event be the last action of the runLoop? _ember.default.run.once(this, 'trigger', 'didLoad'); } }); }); define('ember-data/-private/system/record-arrays/filtered-record-array', ['exports', 'ember', 'ember-data/-private/system/record-arrays/record-array'], function (exports, _ember, _emberDataPrivateSystemRecordArraysRecordArray) { /** @module ember-data */ var get = _ember.default.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 */ exports.default = _emberDataPrivateSystemRecordArraysRecordArray.default.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.peekAll('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.default.observer('filterFunction', function () { _ember.default.run.once(this, this._updateFilter); }) }); }); define("ember-data/-private/system/record-arrays/record-array", ["exports", "ember", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/snapshot-record-array"], function (exports, _ember, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemSnapshotRecordArray) { var get = _ember.default.get; var set = _ember.default.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 */ exports.default = _ember.default.ArrayProxy.extend(_ember.default.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 finished loading data. Example ```javascript var people = store.peekAll('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.peekAll('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'); var internalModel = content.objectAt(index); return internalModel && internalModel.getRecord(); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.peekAll('person'); people.get('isUpdating'); // false people.update().then(function() { people.get('isUpdating'); // false }); people.get('isUpdating'); // true ``` @method update */ update: function () { if (get(this, 'isUpdating')) { return; } this.set('isUpdating', true); return this._update(); }, /* Update this RecordArray and return a promise which resolves once the update is finished. */ _update: function () { var store = get(this, 'store'); var modelName = get(this, 'type.modelName'); return store.findAll(modelName, { reload: true }); }, /** Adds an internal model to the `RecordArray` without duplicates @method addInternalModel @private @param {InternalModel} internalModel @param {number} an optional index to insert at */ addInternalModel: function (internalModel, idx) { var content = get(this, 'content'); if (idx === undefined) { content.addObject(internalModel); } else if (!content.includes(internalModel)) { content.insertAt(idx, internalModel); } }, /** Removes an internalModel to the `RecordArray`. @method removeInternalModel @private @param {InternalModel} internalModel */ removeInternalModel: function (internalModel) { get(this, 'content').removeObject(internalModel); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.peekAll('message'); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function () { var recordArray = this; var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); var promise = _ember.default.RSVP.all(this.invoke("save"), promiseLabel).then(function (array) { return recordArray; }, null, "DS: RecordArray#save return RecordArray"); return _emberDataPrivateSystemPromiseProxies.PromiseArray.create({ promise: promise }); }, _dissociateFromOwnRecords: function () { var _this = this; this.get('content').forEach(function (record) { var recordArrays = record._recordArrays; if (recordArrays) { recordArrays.delete(_this); } }); }, /** @method _unregisterFromManager @private */ _unregisterFromManager: function () { var manager = get(this, 'manager'); manager.unregisterRecordArray(this); }, willDestroy: function () { this._unregisterFromManager(); this._dissociateFromOwnRecords(); set(this, 'content', undefined); set(this, 'length', 0); this._super.apply(this, arguments); }, createSnapshot: function (options) { var meta = this.get('meta'); return new _emberDataPrivateSystemSnapshotRecordArray.default(this, meta, options); } }); }); /** @module ember-data */ define('ember-data/-private/system/references', ['exports', 'ember-data/-private/system/references/record', 'ember-data/-private/system/references/belongs-to', 'ember-data/-private/system/references/has-many'], function (exports, _emberDataPrivateSystemReferencesRecord, _emberDataPrivateSystemReferencesBelongsTo, _emberDataPrivateSystemReferencesHasMany) { exports.RecordReference = _emberDataPrivateSystemReferencesRecord.default; exports.BelongsToReference = _emberDataPrivateSystemReferencesBelongsTo.default; exports.HasManyReference = _emberDataPrivateSystemReferencesHasMany.default; }); define('ember-data/-private/system/references/belongs-to', ['exports', 'ember-data/model', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/features', 'ember-data/-private/debug'], function (exports, _emberDataModel, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateFeatures, _emberDataPrivateDebug) { var BelongsToReference = function (store, parentInternalModel, belongsToRelationship) { this._super$constructor(store, parentInternalModel); this.belongsToRelationship = belongsToRelationship; this.type = belongsToRelationship.relationshipMeta.type; this.parent = parentInternalModel.recordReference; // TODO inverse }; BelongsToReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference.default.prototype); BelongsToReference.prototype.constructor = BelongsToReference; BelongsToReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference.default; BelongsToReference.prototype.remoteType = function () { if (this.belongsToRelationship.link) { return "link"; } return "id"; }; BelongsToReference.prototype.id = function () { var inverseRecord = this.belongsToRelationship.inverseRecord; return inverseRecord && inverseRecord.id; }; BelongsToReference.prototype.link = function () { return this.belongsToRelationship.link; }; BelongsToReference.prototype.meta = function () { return this.belongsToRelationship.meta; }; BelongsToReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember.default.RSVP.resolve(objectOrPromise).then(function (data) { var record; if (data instanceof _emberDataModel.default) { if ((0, _emberDataPrivateFeatures.default)('ds-overhaul-references')) { (0, _emberDataPrivateDebug.deprecate)("BelongsToReference#push(DS.Model) is deprecated. Update relationship via `model.set('relationshipName', value)` instead.", false, { id: 'ds.references.belongs-to.push-record', until: '3.0' }); } record = data; } else { record = _this.store.push(data); } (0, _emberDataPrivateDebug.assertPolymorphicType)(_this.internalModel, _this.belongsToRelationship.relationshipMeta, record._internalModel); _this.belongsToRelationship.setCanonicalRecord(record._internalModel); return record; }); }; BelongsToReference.prototype.value = function () { var inverseRecord = this.belongsToRelationship.inverseRecord; if (inverseRecord && inverseRecord.record) { return inverseRecord.record; } return null; }; BelongsToReference.prototype.load = function () { var _this2 = this; if (this.remoteType() === "id") { return this.belongsToRelationship.getRecord(); } if (this.remoteType() === "link") { return this.belongsToRelationship.findLink().then(function (internalModel) { return _this2.value(); }); } }; BelongsToReference.prototype.reload = function () { var _this3 = this; return this.belongsToRelationship.reload().then(function (internalModel) { return _this3.value(); }); }; exports.default = BelongsToReference; }); define('ember-data/-private/system/references/has-many', ['exports', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/debug', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateDebug, _emberDataPrivateFeatures) { var get = _ember.default.get; var HasManyReference = function (store, parentInternalModel, hasManyRelationship) { this._super$constructor(store, parentInternalModel); this.hasManyRelationship = hasManyRelationship; this.type = hasManyRelationship.relationshipMeta.type; this.parent = parentInternalModel.recordReference; // TODO inverse }; HasManyReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference.default.prototype); HasManyReference.prototype.constructor = HasManyReference; HasManyReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference.default; HasManyReference.prototype.remoteType = function () { if (this.hasManyRelationship.link) { return "link"; } return "ids"; }; HasManyReference.prototype.link = function () { return this.hasManyRelationship.link; }; HasManyReference.prototype.ids = function () { var members = this.hasManyRelationship.members; var ids = members.toArray().map(function (internalModel) { return internalModel.id; }); return ids; }; HasManyReference.prototype.meta = function () { return this.hasManyRelationship.manyArray.meta; }; HasManyReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember.default.RSVP.resolve(objectOrPromise).then(function (payload) { var array = payload; if ((0, _emberDataPrivateFeatures.default)("ds-overhaul-references")) { (0, _emberDataPrivateDebug.deprecate)("HasManyReference#push(array) is deprecated. Push a JSON-API document instead.", !Array.isArray(payload), { id: 'ds.references.has-many.push-array', until: '3.0' }); } var useLegacyArrayPush = true; if (typeof payload === "object" && payload.data) { array = payload.data; useLegacyArrayPush = array.length && array[0].data; if ((0, _emberDataPrivateFeatures.default)('ds-overhaul-references')) { (0, _emberDataPrivateDebug.deprecate)("HasManyReference#push() expects a valid JSON-API document.", !useLegacyArrayPush, { id: 'ds.references.has-many.push-invalid-json-api', until: '3.0' }); } } if (!(0, _emberDataPrivateFeatures.default)('ds-overhaul-references')) { useLegacyArrayPush = true; } var internalModels = undefined; if (useLegacyArrayPush) { internalModels = array.map(function (obj) { var record = _this.store.push(obj); (0, _emberDataPrivateDebug.runInDebug)(function () { var relationshipMeta = _this.hasManyRelationship.relationshipMeta; (0, _emberDataPrivateDebug.assertPolymorphicType)(_this.internalModel, relationshipMeta, record._internalModel); }); return record._internalModel; }); } else { var records = _this.store.push(payload); internalModels = _ember.default.A(records).mapBy('_internalModel'); (0, _emberDataPrivateDebug.runInDebug)(function () { internalModels.forEach(function (internalModel) { var relationshipMeta = _this.hasManyRelationship.relationshipMeta; (0, _emberDataPrivateDebug.assertPolymorphicType)(_this.internalModel, relationshipMeta, internalModel); }); }); } _this.hasManyRelationship.computeChanges(internalModels); return _this.hasManyRelationship.manyArray; }); }; HasManyReference.prototype._isLoaded = function () { var hasData = get(this.hasManyRelationship, 'hasData'); if (!hasData) { return false; } var members = this.hasManyRelationship.members.toArray(); var isEveryLoaded = members.every(function (internalModel) { return internalModel.isLoaded() === true; }); return isEveryLoaded; }; HasManyReference.prototype.value = function () { if (this._isLoaded()) { return this.hasManyRelationship.manyArray; } return null; }; HasManyReference.prototype.load = function () { if (!this._isLoaded()) { return this.hasManyRelationship.getRecords(); } var manyArray = this.hasManyRelationship.manyArray; return _ember.default.RSVP.resolve(manyArray); }; HasManyReference.prototype.reload = function () { return this.hasManyRelationship.reload(); }; exports.default = HasManyReference; }); define('ember-data/-private/system/references/record', ['exports', 'ember', 'ember-data/-private/system/references/reference'], function (exports, _ember, _emberDataPrivateSystemReferencesReference) { var RecordReference = function (store, internalModel) { this._super$constructor(store, internalModel); this.type = internalModel.modelName; this._id = internalModel.id; }; RecordReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference.default.prototype); RecordReference.prototype.constructor = RecordReference; RecordReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference.default; RecordReference.prototype.id = function () { return this._id; }; RecordReference.prototype.remoteType = function () { return 'identity'; }; RecordReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember.default.RSVP.resolve(objectOrPromise).then(function (data) { var record = _this.store.push(data); return record; }); }; RecordReference.prototype.value = function () { return this.internalModel.record; }; RecordReference.prototype.load = function () { return this.store.findRecord(this.type, this._id); }; RecordReference.prototype.reload = function () { var record = this.value(); if (record) { return record.reload(); } return this.load(); }; exports.default = RecordReference; }); define("ember-data/-private/system/references/reference", ["exports"], function (exports) { var Reference = function (store, internalModel) { this.store = store; this.internalModel = internalModel; }; Reference.prototype = { constructor: Reference }; exports.default = Reference; }); define('ember-data/-private/system/relationship-meta', ['exports', 'ember-inflector', 'ember-data/-private/system/normalize-model-name'], function (exports, _emberInflector, _emberDataPrivateSystemNormalizeModelName) { exports.typeForRelationshipMeta = typeForRelationshipMeta; exports.relationshipFromMeta = relationshipFromMeta; function typeForRelationshipMeta(meta) { var modelName; modelName = meta.type || meta.key; if (meta.kind === 'hasMany') { modelName = (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(modelName)); } return modelName; } function relationshipFromMeta(meta) { return { key: meta.key, kind: meta.kind, type: typeForRelationshipMeta(meta), options: meta.options, parentType: meta.parentType, isRelationship: true }; } }); define("ember-data/-private/system/relationships/belongs-to", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/normalize-model-name"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeModelName) { exports.default = belongsTo; /** `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`: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ profile: DS.belongsTo('profile') }); ``` ```app/models/profile.js import DS from 'ember-data'; export default 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: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the key name. ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo() }); ``` will lookup for a Post type. @namespace @method belongsTo @for DS @param {String} modelName (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function belongsTo(modelName, options) { var opts, userEnteredModelName; if (typeof modelName === 'object') { opts = modelName; userEnteredModelName = undefined; } else { opts = options; userEnteredModelName = modelName; } if (typeof userEnteredModelName === 'string') { userEnteredModelName = (0, _emberDataPrivateSystemNormalizeModelName.default)(userEnteredModelName); } (0, _emberDataPrivateDebug.assert)("The first argument to DS.belongsTo must be a string representing a model type key, not an instance of " + _ember.default.inspect(userEnteredModelName) + ". E.g., to define a relation to the Person model, use DS.belongsTo('person')", typeof userEnteredModelName === 'string' || typeof userEnteredModelName === 'undefined'); opts = opts || {}; var meta = { type: userEnteredModelName, isRelationship: true, options: opts, kind: 'belongsTo', key: null }; return _ember.default.computed({ get: function (key) { if (opts.hasOwnProperty('serialize')) { (0, _emberDataPrivateDebug.warn)("You provided a serialize option on the \"" + key + "\" property in the \"" + this._internalModel.modelName + "\" class, this belongs in the serializer. See DS.Serializer and it's implementations http://emberjs.com/api/data/classes/DS.Serializer.html", false, { id: 'ds.model.serialize-option-in-belongs-to' }); } if (opts.hasOwnProperty('embedded')) { (0, _emberDataPrivateDebug.warn)("You provided an embedded option on the \"" + key + "\" property in the \"" + this._internalModel.modelName + "\" class, this belongs in the serializer. See DS.EmbeddedRecordsMixin http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html", false, { id: 'ds.model.embedded-option-in-belongs-to' }); } return this._internalModel._relationships.get(key).getRecord(); }, set: function (key, value) { if (value === undefined) { value = null; } if (value && value.then) { this._internalModel._relationships.get(key).setRecordPromise(value); } else if (value) { this._internalModel._relationships.get(key).setRecord(value._internalModel); } else { this._internalModel._relationships.get(key).setRecord(value); } return this._internalModel._relationships.get(key).getRecord(); } }).meta(meta); } /* These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. */ var BelongsToMixin = _ember.default.Mixin.create({ notifyBelongsToChanged: function (key) { this.notifyPropertyChange(key); } }); exports.BelongsToMixin = BelongsToMixin; }); define("ember-data/-private/system/relationships/ext", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/relationship-meta", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemRelationshipMeta, _emberDataPrivateSystemEmptyObject) { var get = _ember.default.get; var Map = _ember.default.Map; var MapWithDefault = _ember.default.MapWithDefault; var relationshipsDescriptor = _ember.default.computed(function () { if (_ember.default.testing === true && relationshipsDescriptor._cacheable === true) { relationshipsDescriptor._cacheable = false; } var map = new 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((0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta)); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }).readOnly(); var relatedTypesDescriptor = _ember.default.computed(function () { var _this = this; if (_ember.default.testing === true && relatedTypesDescriptor._cacheable === true) { relatedTypesDescriptor._cacheable = false; } var modelName; var types = _ember.default.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; modelName = (0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta); (0, _emberDataPrivateDebug.assert)("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", modelName); if (!types.includes(modelName)) { (0, _emberDataPrivateDebug.assert)("Trying to sideload " + name + " on " + _this.toString() + " but the type doesn't exist.", !!modelName); types.push(modelName); } } }); return types; }).readOnly(); var relationshipsByNameDescriptor = _ember.default.computed(function () { if (_ember.default.testing === true && relationshipsByNameDescriptor._cacheable === true) { relationshipsByNameDescriptor._cacheable = false; } var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { meta.key = name; var relationship = (0, _emberDataPrivateSystemRelationshipMeta.relationshipFromMeta)(meta); relationship.type = (0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta); map.set(name, relationship); } }); return map; }).readOnly(); /** @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 */ var DidDefinePropertyMixin = _ember.default.Mixin.create({ /** 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 {Object} proto @param {String} key @param {Ember.ComputedProperty} value */ didDefineProperty: function (proto, key, value) { // Check if the value being set is a computed property. if (value instanceof _ember.default.ComputedProperty) { // 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(); meta.parentType = proto.constructor; } } }); exports.DidDefinePropertyMixin = DidDefinePropertyMixin; /* 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. */ var RelationshipsClassMethodsMixin = _ember.default.Mixin.create({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```app/models/post.js import DS from 'ember-data'; export default 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 @param {store} store an instance of DS.Store @return {DS.Model} the type of the relationship, or undefined */ typeForRelationship: function (name, store) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && store.modelFor(relationship.type); }, inverseMap: _ember.default.computed(function () { return new _emberDataPrivateSystemEmptyObject.default(); }), /** Find the relationship which is the inverse of the one asked for. For example, if you define models like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('message') }); ``` ```app/models/message.js import DS from 'ember-data'; export default DS.Model.extend({ owner: DS.belongsTo('post') }); ``` App.Post.inverseFor('comments') -> { type: App.Message, name: 'owner', kind: 'belongsTo' } App.Message.inverseFor('owner') -> { type: App.Post, name: 'comments', kind: 'hasMany' } @method inverseFor @static @param {String} name the name of the relationship @return {Object} the inverse relationship, or null */ inverseFor: function (name, store) { var inverseMap = get(this, 'inverseMap'); if (inverseMap[name]) { return inverseMap[name]; } else { var inverse = this._findInverseFor(name, store); inverseMap[name] = inverse; return inverse; } }, //Calculate the inverse, ignoring the cache _findInverseFor: function (name, store) { var inverseType = this.typeForRelationship(name, store); if (!inverseType) { return null; } var propertyMeta = this.metaForProperty(name); //If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })` var options = propertyMeta.options; if (options.inverse === null) { return null; } var inverseName, inverseKind, inverse; //If inverse is specified manually, return the inverse if (options.inverse) { inverseName = options.inverse; inverse = _ember.default.get(inverseType, 'relationshipsByName').get(inverseName); (0, _emberDataPrivateDebug.assert)("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.modelName + "' model. This is most likely due to a missing attribute on your model definition.", !_ember.default.isNone(inverse)); inverseKind = inverse.kind; } else { //No inverse was specified manually, we need to use a heuristic to guess one if (propertyMeta.type === propertyMeta.parentType.modelName) { (0, _emberDataPrivateDebug.warn)("Detected a reflexive relationship by the name of '" + name + "' without an inverse option. Look at http://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.", false, { id: 'ds.model.reflexive-relationship-without-inverse' }); } var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } var filteredRelationships = possibleRelationships.filter(function (possibleRelationship) { var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options; return name === optionsForRelationship.inverse; }); (0, _emberDataPrivateDebug.assert)("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " + inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", filteredRelationships.length < 2); if (filteredRelationships.length === 1) { possibleRelationships = filteredRelationships; } (0, _emberDataPrivateDebug.assert)("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, relationshipsSoFar) { var possibleRelationships = relationshipsSoFar || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return possibleRelationships; } var relationships = relationshipMap.get(type.modelName); relationships = relationships.filter(function (relationship) { var optionsForRelationship = inverseType.metaForProperty(relationship.name).options; if (!optionsForRelationship.inverse) { return true; } return name === optionsForRelationship.inverse; }); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationships); } //Recurse to support polymorphism 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: ```app/models/blog.js import DS from 'ember-data'; export default 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 import Ember from 'ember'; import Blog from 'app/models/blog'; var relationships = Ember.get(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: relationshipsDescriptor, /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relationshipNames = Ember.get(Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: _ember.default.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: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relatedTypes = Ember.get(Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: relatedTypesDescriptor, /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relationshipsByName = Ember.get(Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: relationshipsByNameDescriptor, /** 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: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); ``` ```js import Ember from 'ember'; import Blog from 'app/models/blog'; var fields = Ember.get(Blog, 'fields'); fields.forEach(function(kind, field) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: _ember.default.computed(function () { var map = 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; }).readOnly(), /** 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 (relationship, name) { 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) { var relationshipTypes = get(this, 'relatedTypes'); for (var i = 0; i < relationshipTypes.length; i++) { var type = relationshipTypes[i]; callback.call(binding, type); } }, determineRelationshipType: function (knownSide, store) { var knownKey = knownSide.key; var knownKind = knownSide.kind; var inverse = this.inverseFor(knownKey, store); // let key; var otherKind = undefined; if (!inverse) { return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone'; } // key = inverse.name; otherKind = inverse.kind; if (otherKind === 'belongsTo') { return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne'; } else { return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany'; } } }); exports.RelationshipsClassMethodsMixin = RelationshipsClassMethodsMixin; var RelationshipsInstanceMethodsMixin = _ember.default.Mixin.create({ /** 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. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, descriptor); ``` - `name` the name of the current property in the iteration - `descriptor` the meta object that describes this relationship The relationship descriptor argument is an object with the following properties. - **key** <span class="type">String</span> the name of this relationship on the Model - **kind** <span class="type">String</span> "hasMany" or "belongsTo" - **options** <span class="type">Object</span> the original options hash passed when the relationship was declared - **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship - **type** <span class="type">String</span> the type name of the related Model 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 ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachRelationship(function(name, descriptor) { if (descriptor.kind === 'hasMany') { var serializedHasManyName = name.toUpperCase() + '_IDS'; json[serializedHasManyName] = record.get(name).mapBy('id'); } }); return json; } }); ``` @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); }, relationshipFor: function (name) { return get(this.constructor, 'relationshipsByName').get(name); }, inverseFor: function (key) { return this.constructor.inverseFor(key, this.store); } }); exports.RelationshipsInstanceMethodsMixin = RelationshipsInstanceMethodsMixin; }); define("ember-data/-private/system/relationships/has-many", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/is-array-like"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemIsArrayLike) { exports.default = hasMany; /** `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: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ tags: DS.hasMany('tag') }); ``` ```app/models/tag.js import DS from 'ember-data'; export default DS.Model.extend({ posts: DS.hasMany('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the singularized key name. ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ tags: DS.hasMany() }); ``` will lookup for a Tag type. #### 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: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ onePost: DS.belongsTo('post'), twoPost: DS.belongsTo('post'), redPost: DS.belongsTo('post'), bluePost: DS.belongsTo('post') }); ``` ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.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} type (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function hasMany(type, options) { if (typeof type === 'object') { options = type; type = undefined; } (0, _emberDataPrivateDebug.assert)("The first argument to DS.hasMany must be a string representing a model type key, not an instance of " + _ember.default.inspect(type) + ". E.g., to define a relation to the Comment model, use DS.hasMany('comment')", typeof type === 'string' || typeof type === 'undefined'); options = options || {}; if (typeof type === 'string') { type = (0, _emberDataPrivateSystemNormalizeModelName.default)(type); } // Metadata about relationships is stored on the meta of // the relationship. This is used for introspection and // serialization. Note that `key` is populated lazily // the first time the CP is called. var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany', key: null }; return _ember.default.computed({ get: function (key) { var relationship = this._internalModel._relationships.get(key); return relationship.getRecords(); }, set: function (key, records) { (0, _emberDataPrivateDebug.assert)("You must pass an array of records to set a hasMany relationship", (0, _emberDataPrivateSystemIsArrayLike.default)(records)); (0, _emberDataPrivateDebug.assert)("All elements of a hasMany relationship must be instances of DS.Model, you passed " + _ember.default.inspect(records), (function () { return _ember.default.A(records).every(function (record) { return record.hasOwnProperty('_internalModel') === true; }); })()); var relationship = this._internalModel._relationships.get(key); relationship.clear(); relationship.addRecords(_ember.default.A(records).mapBy('_internalModel')); return relationship.getRecords(); } }).meta(meta); } var HasManyMixin = _ember.default.Mixin.create({ notifyHasManyAdded: function (key) { //We need to notifyPropertyChange in the adding case because we need to make sure //we fetch the newly added record in case it is unloaded //TODO(Igor): Consider whether we could do this only if the record state is unloaded //Goes away once hasMany is double promisified this.notifyPropertyChange(key); } }); exports.HasManyMixin = HasManyMixin; }); /** @module ember-data */ define("ember-data/-private/system/relationships/state/belongs-to", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemRelationshipsStateRelationship) { exports.default = BelongsToRelationship; function BelongsToRelationship(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.record = record; this.key = relationshipMeta.key; this.inverseRecord = null; this.canonicalState = null; } BelongsToRelationship.prototype = Object.create(_emberDataPrivateSystemRelationshipsStateRelationship.default.prototype); BelongsToRelationship.prototype.constructor = BelongsToRelationship; BelongsToRelationship.prototype._super$constructor = _emberDataPrivateSystemRelationshipsStateRelationship.default; BelongsToRelationship.prototype.setRecord = function (newRecord) { if (newRecord) { this.addRecord(newRecord); } else if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.setHasData(true); this.setHasLoaded(true); }; BelongsToRelationship.prototype.setCanonicalRecord = function (newRecord) { if (newRecord) { this.addCanonicalRecord(newRecord); } else if (this.canonicalState) { this.removeCanonicalRecord(this.canonicalState); } this.flushCanonicalLater(); this.setHasData(true); this.setHasLoaded(true); }; BelongsToRelationship.prototype._super$addCanonicalRecord = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.addCanonicalRecord; BelongsToRelationship.prototype.addCanonicalRecord = function (newRecord) { if (this.canonicalMembers.has(newRecord)) { return; } if (this.canonicalState) { this.removeCanonicalRecord(this.canonicalState); } this.canonicalState = newRecord; this._super$addCanonicalRecord(newRecord); }; BelongsToRelationship.prototype._super$flushCanonical = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.flushCanonical; BelongsToRelationship.prototype.flushCanonical = function () { //temporary fix to not remove newly created records if server returned null. //TODO remove once we have proper diffing if (this.inverseRecord && this.inverseRecord.isNew() && !this.canonicalState) { return; } this.inverseRecord = this.canonicalState; this.record.notifyBelongsToChanged(this.key); this._super$flushCanonical(); }; BelongsToRelationship.prototype._super$addRecord = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.addRecord; BelongsToRelationship.prototype.addRecord = function (newRecord) { if (this.members.has(newRecord)) { return; } (0, _emberDataPrivateDebug.assertPolymorphicType)(this.record, this.relationshipMeta, newRecord); if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.inverseRecord = newRecord; this._super$addRecord(newRecord); this.record.notifyBelongsToChanged(this.key); }; BelongsToRelationship.prototype.setRecordPromise = function (newPromise) { var content = newPromise.get && newPromise.get('content'); (0, _emberDataPrivateDebug.assert)("You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call.", content !== undefined); this.setRecord(content ? content._internalModel : content); }; BelongsToRelationship.prototype._super$removeRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.removeRecordFromOwn; BelongsToRelationship.prototype.removeRecordFromOwn = function (record) { if (!this.members.has(record)) { return; } this.inverseRecord = null; this._super$removeRecordFromOwn(record); this.record.notifyBelongsToChanged(this.key); }; BelongsToRelationship.prototype._super$removeCanonicalRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.removeCanonicalRecordFromOwn; BelongsToRelationship.prototype.removeCanonicalRecordFromOwn = function (record) { if (!this.canonicalMembers.has(record)) { return; } this.canonicalState = null; this._super$removeCanonicalRecordFromOwn(record); }; BelongsToRelationship.prototype.findRecord = function () { if (this.inverseRecord) { return this.store._findByInternalModel(this.inverseRecord); } else { return _ember.default.RSVP.Promise.resolve(null); } }; BelongsToRelationship.prototype.fetchLink = function () { var _this = this; return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function (record) { if (record) { _this.addRecord(record); } return record; }); }; BelongsToRelationship.prototype.getRecord = function () { var _this2 = this; //TODO(Igor) flushCanonical here once our syncing is not stupid if (this.isAsync) { var promise; if (this.link) { if (this.hasLoaded) { promise = this.findRecord(); } else { promise = this.findLink().then(function () { return _this2.findRecord(); }); } } else { promise = this.findRecord(); } return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ promise: promise, content: this.inverseRecord ? this.inverseRecord.getRecord() : null }); } else { if (this.inverseRecord === null) { return null; } var toReturn = this.inverseRecord.getRecord(); (0, _emberDataPrivateDebug.assert)("You looked up the '" + this.key + "' relationship on a '" + this.record.type.modelName + "' with id " + this.record.id + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)", toReturn === null || !toReturn.get('isEmpty')); return toReturn; } }; BelongsToRelationship.prototype.reload = function () { // TODO handle case when reload() is triggered multiple times if (this.link) { return this.fetchLink(); } // reload record, if it is already loaded if (this.inverseRecord && this.inverseRecord.record) { return this.inverseRecord.record.reload(); } return this.findRecord(); }; }); define("ember-data/-private/system/relationships/state/create", ["exports", "ember", "ember-data/-private/system/relationships/state/has-many", "ember-data/-private/system/relationships/state/belongs-to", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateSystemRelationshipsStateHasMany, _emberDataPrivateSystemRelationshipsStateBelongsTo, _emberDataPrivateSystemEmptyObject) { exports.default = Relationships; var get = _ember.default.get; function shouldFindInverse(relationshipMeta) { var options = relationshipMeta.options; return !(options && options.inverse === null); } function createRelationshipFor(record, relationshipMeta, store) { var inverseKey = undefined; var inverse = null; if (shouldFindInverse(relationshipMeta)) { inverse = record.type.inverseFor(relationshipMeta.key, store); } if (inverse) { inverseKey = inverse.name; } if (relationshipMeta.kind === 'hasMany') { return new _emberDataPrivateSystemRelationshipsStateHasMany.default(store, record, inverseKey, relationshipMeta); } else { return new _emberDataPrivateSystemRelationshipsStateBelongsTo.default(store, record, inverseKey, relationshipMeta); } } function Relationships(record) { this.record = record; this.initializedRelationships = new _emberDataPrivateSystemEmptyObject.default(); } Relationships.prototype.has = function (key) { return !!this.initializedRelationships[key]; }; Relationships.prototype.get = function (key) { var relationships = this.initializedRelationships; var relationshipsByName = get(this.record.type, 'relationshipsByName'); if (!relationships[key] && relationshipsByName.get(key)) { relationships[key] = createRelationshipFor(this.record, relationshipsByName.get(key), this.record.store); } return relationships[key]; }; }); define("ember-data/-private/system/relationships/state/has-many", ["exports", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/relationships/state/relationship", "ember-data/-private/system/ordered-set", "ember-data/-private/system/many-array"], function (exports, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemRelationshipsStateRelationship, _emberDataPrivateSystemOrderedSet, _emberDataPrivateSystemManyArray) { exports.default = ManyRelationship; function ManyRelationship(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.belongsToType = relationshipMeta.type; this.canonicalState = []; this.manyArray = _emberDataPrivateSystemManyArray.default.create({ canonicalState: this.canonicalState, store: this.store, relationship: this, type: this.store.modelFor(this.belongsToType), record: record }); this.isPolymorphic = relationshipMeta.options.polymorphic; this.manyArray.isPolymorphic = this.isPolymorphic; } ManyRelationship.prototype = Object.create(_emberDataPrivateSystemRelationshipsStateRelationship.default.prototype); ManyRelationship.prototype.constructor = ManyRelationship; ManyRelationship.prototype._super$constructor = _emberDataPrivateSystemRelationshipsStateRelationship.default; ManyRelationship.prototype.destroy = function () { this.manyArray.destroy(); }; ManyRelationship.prototype._super$updateMeta = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.updateMeta; ManyRelationship.prototype.updateMeta = function (meta) { this._super$updateMeta(meta); this.manyArray.set('meta', meta); }; ManyRelationship.prototype._super$addCanonicalRecord = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.addCanonicalRecord; ManyRelationship.prototype.addCanonicalRecord = function (record, idx) { if (this.canonicalMembers.has(record)) { return; } if (idx !== undefined) { this.canonicalState.splice(idx, 0, record); } else { this.canonicalState.push(record); } this._super$addCanonicalRecord(record, idx); }; ManyRelationship.prototype._super$addRecord = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.addRecord; ManyRelationship.prototype.addRecord = function (record, idx) { if (this.members.has(record)) { return; } this._super$addRecord(record, idx); this.manyArray.internalAddRecords([record], idx); }; ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.removeCanonicalRecordFromOwn; ManyRelationship.prototype.removeCanonicalRecordFromOwn = function (record, idx) { var i = idx; if (!this.canonicalMembers.has(record)) { return; } if (i === undefined) { i = this.canonicalState.indexOf(record); } if (i > -1) { this.canonicalState.splice(i, 1); } this._super$removeCanonicalRecordFromOwn(record, idx); }; ManyRelationship.prototype._super$flushCanonical = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.flushCanonical; ManyRelationship.prototype.flushCanonical = function () { this.manyArray.flushCanonical(); this._super$flushCanonical(); }; ManyRelationship.prototype._super$removeRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.removeRecordFromOwn; ManyRelationship.prototype.removeRecordFromOwn = function (record, idx) { if (!this.members.has(record)) { return; } this._super$removeRecordFromOwn(record, idx); if (idx !== undefined) { //TODO(Igor) not used currently, fix this.manyArray.currentState.removeAt(idx); } else { this.manyArray.internalRemoveRecords([record]); } }; ManyRelationship.prototype.notifyRecordRelationshipAdded = function (record, idx) { (0, _emberDataPrivateDebug.assertPolymorphicType)(this.record, this.relationshipMeta, record); this.record.notifyHasManyAdded(this.key, record, idx); }; ManyRelationship.prototype.reload = function () { var _this = this; var manyArrayLoadedState = this.manyArray.get('isLoaded'); if (this._loadingPromise) { if (this._loadingPromise.get('isPending')) { return this._loadingPromise; } if (this._loadingPromise.get('isRejected')) { this.manyArray.set('isLoaded', manyArrayLoadedState); } } if (this.link) { this._loadingPromise = (0, _emberDataPrivateSystemPromiseProxies.promiseManyArray)(this.fetchLink(), 'Reload with link'); return this._loadingPromise; } else { this._loadingPromise = (0, _emberDataPrivateSystemPromiseProxies.promiseManyArray)(this.store.scheduleFetchMany(this.manyArray.toArray()).then(function () { return _this.manyArray; }), 'Reload with ids'); return this._loadingPromise; } }; ManyRelationship.prototype.computeChanges = function (records) { var members = this.canonicalMembers; var recordsToRemove = []; var length; var record; var i; records = setForArray(records); members.forEach(function (member) { if (records.has(member)) { return; } recordsToRemove.push(member); }); this.removeCanonicalRecords(recordsToRemove); // Using records.toArray() since currently using // removeRecord can modify length, messing stuff up // forEach since it directly looks at "length" each // iteration records = records.toArray(); length = records.length; for (i = 0; i < length; i++) { record = records[i]; this.removeCanonicalRecord(record); this.addCanonicalRecord(record, i); } }; ManyRelationship.prototype.fetchLink = function () { var _this2 = this; return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function (records) { if (records.hasOwnProperty('meta')) { _this2.updateMeta(records.meta); } _this2.store._backburner.join(function () { _this2.updateRecordsFromAdapter(records); _this2.manyArray.set('isLoaded', true); }); return _this2.manyArray; }); }; ManyRelationship.prototype.findRecords = function () { var _this3 = this; var manyArray = this.manyArray.toArray(); var internalModels = new Array(manyArray.length); for (var i = 0; i < manyArray.length; i++) { internalModels[i] = manyArray[i]._internalModel; } //TODO CLEANUP return this.store.findMany(internalModels).then(function () { if (!_this3.manyArray.get('isDestroyed')) { //Goes away after the manyArray refactor _this3.manyArray.set('isLoaded', true); } return _this3.manyArray; }); }; ManyRelationship.prototype.notifyHasManyChanged = function () { this.record.notifyHasManyAdded(this.key); }; ManyRelationship.prototype.getRecords = function () { var _this4 = this; //TODO(Igor) sync server here, once our syncing is not stupid if (this.isAsync) { var promise; if (this.link) { if (this.hasLoaded) { promise = this.findRecords(); } else { promise = this.findLink().then(function () { return _this4.findRecords(); }); } } else { promise = this.findRecords(); } this._loadingPromise = _emberDataPrivateSystemPromiseProxies.PromiseManyArray.create({ content: this.manyArray, promise: promise }); return this._loadingPromise; } else { (0, _emberDataPrivateDebug.assert)("You looked up the '" + this.key + "' relationship on a '" + this.record.type.modelName + "' with id " + this.record.id + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", this.manyArray.isEvery('isEmpty', false)); //TODO(Igor) WTF DO I DO HERE? if (!this.manyArray.get('isDestroyed')) { this.manyArray.set('isLoaded', true); } return this.manyArray; } }; function setForArray(array) { var set = new _emberDataPrivateSystemOrderedSet.default(); if (array) { for (var i = 0, l = array.length; i < l; i++) { set.add(array[i]); } } return set; } }); define("ember-data/-private/system/relationships/state/relationship", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/ordered-set"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemOrderedSet) { exports.default = Relationship; function Relationship(store, record, inverseKey, relationshipMeta) { var async = relationshipMeta.options.async; this.members = new _emberDataPrivateSystemOrderedSet.default(); this.canonicalMembers = new _emberDataPrivateSystemOrderedSet.default(); this.store = store; this.key = relationshipMeta.key; this.inverseKey = inverseKey; this.record = record; this.isAsync = typeof async === 'undefined' ? true : async; this.relationshipMeta = relationshipMeta; //This probably breaks for polymorphic relationship in complex scenarios, due to //multiple possible modelNames this.inverseKeyForImplicit = this.record.constructor.modelName + this.key; this.linkPromise = null; this.meta = null; this.hasData = false; this.hasLoaded = false; } Relationship.prototype = { constructor: Relationship, destroy: _ember.default.K, updateMeta: function (meta) { this.meta = meta; }, clear: function () { var members = this.members.list; var member; while (members.length > 0) { member = members[0]; this.removeRecord(member); } }, removeRecords: function (records) { var _this = this; records.forEach(function (record) { return _this.removeRecord(record); }); }, addRecords: function (records, idx) { var _this2 = this; records.forEach(function (record) { _this2.addRecord(record, idx); if (idx !== undefined) { idx++; } }); }, addCanonicalRecords: function (records, idx) { for (var i = 0; i < records.length; i++) { if (idx !== undefined) { this.addCanonicalRecord(records[i], i + idx); } else { this.addCanonicalRecord(records[i]); } } }, addCanonicalRecord: function (record, idx) { if (!this.canonicalMembers.has(record)) { this.canonicalMembers.add(record); if (this.inverseKey) { record._relationships.get(this.inverseKey).addCanonicalRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addCanonicalRecord(this.record); } } this.flushCanonicalLater(); this.setHasData(true); }, removeCanonicalRecords: function (records, idx) { for (var i = 0; i < records.length; i++) { if (idx !== undefined) { this.removeCanonicalRecord(records[i], i + idx); } else { this.removeCanonicalRecord(records[i]); } } }, removeCanonicalRecord: function (record, idx) { if (this.canonicalMembers.has(record)) { this.removeCanonicalRecordFromOwn(record); if (this.inverseKey) { this.removeCanonicalRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalRecord(this.record); } } } this.flushCanonicalLater(); }, addRecord: function (record, idx) { if (!this.members.has(record)) { this.members.addWithIndex(record, idx); this.notifyRecordRelationshipAdded(record, idx); if (this.inverseKey) { record._relationships.get(this.inverseKey).addRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record); } this.record.updateRecordArraysLater(); } this.setHasData(true); }, removeRecord: function (record) { if (this.members.has(record)) { this.removeRecordFromOwn(record); if (this.inverseKey) { this.removeRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record); } } } }, removeRecordFromInverse: function (record) { var inverseRelationship = record._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeRecordFromOwn(this.record); } }, removeRecordFromOwn: function (record) { this.members.delete(record); this.notifyRecordRelationshipRemoved(record); this.record.updateRecordArrays(); }, removeCanonicalRecordFromInverse: function (record) { var inverseRelationship = record._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeCanonicalRecordFromOwn(this.record); } }, removeCanonicalRecordFromOwn: function (record) { this.canonicalMembers.delete(record); this.flushCanonicalLater(); }, flushCanonical: function () { this.willSync = false; //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = []; for (var i = 0; i < this.members.list.length; i++) { if (this.members.list[i].isNew()) { newRecords.push(this.members.list[i]); } } //TODO(Igor) make this less abysmally slow this.members = this.canonicalMembers.copy(); for (i = 0; i < newRecords.length; i++) { this.members.add(newRecords[i]); } }, flushCanonicalLater: function () { var _this3 = this; if (this.willSync) { return; } this.willSync = true; this.store._backburner.join(function () { return _this3.store._backburner.schedule('syncRelationships', _this3, _this3.flushCanonical); }); }, updateLink: function (link) { (0, _emberDataPrivateDebug.warn)("You have pushed a record of type '" + this.record.type.modelName + "' with '" + this.key + "' as a link, but the association is not an async relationship.", this.isAsync, { id: 'ds.store.push-link-for-sync-relationship' }); (0, _emberDataPrivateDebug.assert)("You have pushed a record of type '" + this.record.type.modelName + "' with '" + this.key + "' as a link, but the value of that link is not a string.", typeof link === 'string' || link === null); if (link !== this.link) { this.link = link; this.linkPromise = null; this.setHasLoaded(false); this.record.notifyPropertyChange(this.key); } }, findLink: function () { if (this.linkPromise) { return this.linkPromise; } else { var promise = this.fetchLink(); this.linkPromise = promise; return promise.then(function (result) { return result; }); } }, updateRecordsFromAdapter: function (records) { //TODO(Igor) move this to a proper place //TODO Once we have adapter support, we need to handle updated and canonical changes this.computeChanges(records); this.setHasData(true); this.setHasLoaded(true); }, notifyRecordRelationshipAdded: _ember.default.K, notifyRecordRelationshipRemoved: _ember.default.K, /* `hasData` for a relationship is a flag to indicate if we consider the content of this relationship "known". Snapshots uses this to tell the difference between unknown (`undefined`) or empty (`null`). The reason for this is that we wouldn't want to serialize unknown relationships as `null` as that might overwrite remote state. All relationships for a newly created (`store.createRecord()`) are considered known (`hasData === true`). */ setHasData: function (value) { this.hasData = value; }, /* `hasLoaded` is a flag to indicate if we have gotten data from the adapter or not when the relationship has a link. This is used to be able to tell when to fetch the link and when to return the local data in scenarios where the local state is considered known (`hasData === true`). Updating the link will automatically set `hasLoaded` to `false`. */ setHasLoaded: function (value) { this.hasLoaded = value; } }; }); define('ember-data/-private/system/snapshot-record-array', ['exports'], function (exports) { exports.default = SnapshotRecordArray; /** @module ember-data */ /** @class SnapshotRecordArray @namespace DS @private @constructor @param {Array} snapshots An array of snapshots @param {Object} meta */ function SnapshotRecordArray(recordArray, meta) { var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; /** An array of snapshots @private @property _snapshots @type {Array} */ this._snapshots = null; /** An array of records @private @property _recordArray @type {Array} */ this._recordArray = recordArray; /** Number of records in the array @property length @type {Number} */ this.length = recordArray.get('length'); /** The type of the underlying records for the snapshots in the array, as a DS.Model @property type @type {DS.Model} */ this.type = recordArray.get('type'); /** Meta object @property meta @type {Object} */ this.meta = meta; /** A hash of adapter options @property adapterOptions @type {Object} */ this.adapterOptions = options.adapterOptions; this.include = options.include; } /** Get snapshots of the underlying record array @method snapshots @return {Array} Array of snapshots */ SnapshotRecordArray.prototype.snapshots = function () { if (this._snapshots) { return this._snapshots; } var recordArray = this._recordArray; this._snapshots = recordArray.invoke('createSnapshot'); return this._snapshots; }; }); define("ember-data/-private/system/snapshot", ["exports", "ember", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateSystemEmptyObject) { exports.default = Snapshot; var get = _ember.default.get; /** @class Snapshot @namespace DS @private @constructor @param {DS.Model} internalModel The model to create a snapshot from */ function Snapshot(internalModel) { var _this = this; var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this._attributes = new _emberDataPrivateSystemEmptyObject.default(); this._belongsToRelationships = new _emberDataPrivateSystemEmptyObject.default(); this._belongsToIds = new _emberDataPrivateSystemEmptyObject.default(); this._hasManyRelationships = new _emberDataPrivateSystemEmptyObject.default(); this._hasManyIds = new _emberDataPrivateSystemEmptyObject.default(); var record = internalModel.getRecord(); this.record = record; record.eachAttribute(function (keyName) { return _this._attributes[keyName] = get(record, keyName); }); this.id = internalModel.id; this._internalModel = internalModel; this.type = internalModel.type; this.modelName = internalModel.type.modelName; /** A hash of adapter options @property adapterOptions @type {Object} */ this.adapterOptions = options.adapterOptions; this.include = options.include; this._changedAttributes = record.changedAttributes(); } Snapshot.prototype = { constructor: Snapshot, /** The id of the snapshot's underlying record Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.id; // => '1' ``` @property id @type {String} */ id: null, /** The underlying record for this snapshot. Can be used to access methods and properties defined on the record. Example ```javascript var json = snapshot.record.toJSON(); ``` @property record @type {DS.Model} */ record: null, /** The type of the underlying record for this snapshot, as a DS.Model. @property type @type {DS.Model} */ type: null, /** The name of the type of the underlying record for this snapshot, as a string. @property modelName @type {String} */ modelName: null, /** Returns the value of an attribute. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.attr('author'); // => 'Tomster' postSnapshot.attr('title'); // => 'Ember.js rocks' ``` Note: Values are loaded eagerly and cached when the snapshot is created. @method attr @param {String} keyName @return {Object} The attribute value or undefined */ attr: function (keyName) { if (keyName in this._attributes) { return this._attributes[keyName]; } throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no attribute named '" + keyName + "' defined."); }, /** Returns all attributes and their corresponding values. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' } ``` @method attributes @return {Object} All attributes of the current snapshot */ attributes: function () { return _ember.default.copy(this._attributes); }, /** Returns all changed attributes and their old and new values. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postModel.set('title', 'Ember.js rocks!'); postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] } ``` @method changedAttributes @return {Object} All changed attributes of the current snapshot */ changedAttributes: function () { var changedAttributes = new _emberDataPrivateSystemEmptyObject.default(); var changedAttributeKeys = Object.keys(this._changedAttributes); for (var i = 0, _length = changedAttributeKeys.length; i < _length; i++) { var key = changedAttributeKeys[i]; changedAttributes[key] = _ember.default.copy(this._changedAttributes[key]); } return changedAttributes; }, /** Returns the current value of a belongsTo relationship. `belongsTo` takes an optional hash of options as a second parameter, currently supported options are: - `id`: set to `true` if you only want the ID of the related record to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World' }); // store.createRecord('comment', { body: 'Lorem ipsum', post: post }); commentSnapshot.belongsTo('post'); // => DS.Snapshot commentSnapshot.belongsTo('post', { id: true }); // => '1' // store.push('comment', { id: 1, body: 'Lorem ipsum' }); commentSnapshot.belongsTo('post'); // => undefined ``` Calling `belongsTo` will return a new Snapshot as long as there's any known data for the relationship available, such as an ID. If the relationship is known but unset, `belongsTo` will return `null`. If the contents of the relationship is unknown `belongsTo` will return `undefined`. Note: Relationships are loaded lazily and cached upon first access. @method belongsTo @param {String} keyName @param {Object} [options] @return {(DS.Snapshot|String|null|undefined)} A snapshot or ID of a known relationship or null if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ belongsTo: function (keyName, options) { var id = options && options.id; var relationship, inverseRecord, hasData; var result; if (id && keyName in this._belongsToIds) { return this._belongsToIds[keyName]; } if (!id && keyName in this._belongsToRelationships) { return this._belongsToRelationships[keyName]; } relationship = this._internalModel._relationships.get(keyName); if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) { throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no belongsTo relationship named '" + keyName + "' defined."); } hasData = get(relationship, 'hasData'); inverseRecord = get(relationship, 'inverseRecord'); if (hasData) { if (inverseRecord && !inverseRecord.isDeleted()) { if (id) { result = get(inverseRecord, 'id'); } else { result = inverseRecord.createSnapshot(); } } else { result = null; } } if (id) { this._belongsToIds[keyName] = result; } else { this._belongsToRelationships[keyName] = result; } return result; }, /** Returns the current value of a hasMany relationship. `hasMany` takes an optional hash of options as a second parameter, currently supported options are: - `ids`: set to `true` if you only want the IDs of the related records to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] }); postSnapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot] postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3'] // store.push('post', { id: 1, title: 'Hello World' }); postSnapshot.hasMany('comments'); // => undefined ``` Note: Relationships are loaded lazily and cached upon first access. @method hasMany @param {String} keyName @param {Object} [options] @return {(Array|undefined)} An array of snapshots or IDs of a known relationship or an empty array if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ hasMany: function (keyName, options) { var ids = options && options.ids; var relationship, members, hasData; var results; if (ids && keyName in this._hasManyIds) { return this._hasManyIds[keyName]; } if (!ids && keyName in this._hasManyRelationships) { return this._hasManyRelationships[keyName]; } relationship = this._internalModel._relationships.get(keyName); if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) { throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no hasMany relationship named '" + keyName + "' defined."); } hasData = get(relationship, 'hasData'); members = get(relationship, 'members'); if (hasData) { results = []; members.forEach(function (member) { if (!member.isDeleted()) { if (ids) { results.push(member.id); } else { results.push(member.createSnapshot()); } } }); } if (ids) { this._hasManyIds[keyName] = results; } else { this._hasManyRelationships[keyName] = results; } return results; }, /** Iterates through all the attributes of the model, calling the passed function on each attribute. Example ```javascript snapshot.eachAttribute(function(name, meta) { // ... }); ``` @method eachAttribute @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachAttribute: function (callback, binding) { this.record.eachAttribute(callback, binding); }, /** Iterates through all the relationships of the model, calling the passed function on each relationship. Example ```javascript snapshot.eachRelationship(function(name, relationship) { // ... }); ``` @method eachRelationship @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachRelationship: function (callback, binding) { this.record.eachRelationship(callback, binding); }, /** @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function (options) { return this.record.store.serializerFor(this.modelName).serialize(this, options); } }; }); /** @module ember-data */ define('ember-data/-private/system/store', ['exports', 'ember', 'ember-data/model', 'ember-data/-private/debug', 'ember-data/-private/system/normalize-link', 'ember-data/-private/system/normalize-model-name', 'ember-data/adapters/errors', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/store/common', 'ember-data/-private/system/store/serializer-response', 'ember-data/-private/system/store/serializers', 'ember-data/-private/system/store/finders', 'ember-data/-private/utils', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/record-array-manager', 'ember-data/-private/system/store/container-instance-cache', 'ember-data/-private/system/model/internal-model', 'ember-data/-private/system/empty-object', 'ember-data/-private/features'], function (exports, _ember, _emberDataModel, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeLink, _emberDataPrivateSystemNormalizeModelName, _emberDataAdaptersErrors, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStoreCommon, _emberDataPrivateSystemStoreSerializerResponse, _emberDataPrivateSystemStoreSerializers, _emberDataPrivateSystemStoreFinders, _emberDataPrivateUtils, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateSystemStoreContainerInstanceCache, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures) { var badIdFormatAssertion = '`id` passed to `findRecord()` has to be non-empty string or number'; exports.badIdFormatAssertion = badIdFormatAssertion; var Backburner = _ember.default._Backburner; var Map = _ember.default.Map; //Get the materialized model from the internalModel/promise that returns //an internal model and return it in a promiseObject. Useful for returning //from find methods function promiseRecord(internalModel, label) { var toReturn = internalModel.then(function (model) { return model.getRecord(); }); return (0, _emberDataPrivateSystemPromiseProxies.promiseObject)(toReturn, label); } var get = _ember.default.get; var set = _ember.default.set; var once = _ember.default.run.once; var isNone = _ember.default.isNone; var isPresent = _ember.default.isPresent; var Promise = _ember.default.RSVP.Promise; var copy = _ember.default.copy; var Store; var Service = _ember.default.Service; // 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. // * +internalModel+ means a record internalModel object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a DS.Model. /** 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: ```app/services/store.js import DS from 'ember-data'; export default 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 `findRecord()` method: ```javascript store.findRecord('person', 123).then(function (person) { }); ``` 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: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ }); ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. ### Store createRecord() vs. push() vs. pushPayload() The store provides multiple ways to create new record objects. 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 (full or partial) 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. 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#peekAll()`, `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.Service */ exports.Store = Store = Service.extend({ /** @method init @private */ init: function () { this._super.apply(this, arguments); this._backburner = new Backburner(['normalizeRelationships', 'syncRelationships', 'finished']); // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = _emberDataPrivateSystemRecordArrayManager.default.create({ store: this }); this._pendingSave = []; this._instanceCache = new _emberDataPrivateSystemStoreContainerInstanceCache.default((0, _emberDataPrivateUtils.getOwner)(this)); //Used to keep track of all the find requests that need to be coalesced this._pendingFetch = Map.create(); }, /** 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/adapters/custom.js` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.JSONAPIAdapter @type {(DS.Adapter|String)} */ adapter: '-json-api', /** 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) { var snapshot = record._internalModel.createSnapshot(); return snapshot.serialize(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.default.computed('adapter', function () { var adapter = get(this, 'adapter'); (0, _emberDataPrivateDebug.assert)('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name', typeof adapter === 'string'); adapter = this.retrieveManagedInstance('adapter', adapter); 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 a `Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` To create a new instance of a `Post` that has a relationship with a `User` record: ```js var user = this.store.peekRecord('user', 1); store.createRecord('post', { title: "Rails is omakase", user: user }); ``` @method createRecord @param {String} modelName @param {Object} inputProperties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function (modelName, inputProperties) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's createRecord method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var properties = copy(inputProperties) || new _emberDataPrivateSystemEmptyObject.default(); // 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(modelName, properties); } // Coerce ID to a string properties.id = (0, _emberDataPrivateSystemCoerceId.default)(properties.id); var internalModel = this.buildInternalModel(typeClass, properties.id); var record = internalModel.getRecord(); // Move the record out of its initial `empty` state into // the `loaded` state. internalModel.loadedData(); // Set the properties specified on the record. record.setProperties(properties); internalModel.eachRelationship(function (key, descriptor) { internalModel._relationships.get(key).setHasData(true); }); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} modelName @param {Object} properties from the new record @return {String} if the adapter can generate one, an ID */ _generateId: function (modelName, properties) { var adapter = this.adapterFor(modelName); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this, modelName, properties); } 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.findRecord('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function (record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** @method find @param {String} modelName @param {String|Integer} id @param {Object} options @return {Promise} promise @private */ find: function (modelName, id, options) { // The default `model` hook in Ember.Route calls `find(modelName, id)`, // that's why we have to keep this method around even though `findRecord` is // the public way to get a record by modelName and id. if (arguments.length === 1) { (0, _emberDataPrivateDebug.assert)('Using store.find(type) has been removed. Use store.findAll(type) to retrieve all records for a given type.'); } if (_ember.default.typeOf(id) === 'object') { (0, _emberDataPrivateDebug.assert)('Calling store.find() with a query object is no longer supported. Use store.query() instead.'); } if (options) { (0, _emberDataPrivateDebug.assert)('Calling store.find(type, id, { preload: preload }) is no longer supported. Use store.findRecord(type, id, { preload: preload }) instead.'); } (0, _emberDataPrivateDebug.assert)("You need to pass the model name and id to the store's find method", arguments.length === 2); (0, _emberDataPrivateDebug.assert)("You cannot pass `" + _ember.default.inspect(id) + "` as id to the store's find method", _ember.default.typeOf(id) === 'string' || _ember.default.typeOf(id) === 'number'); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); return this.findRecord(modelName, id); }, /** This method returns a record for a given type and id combination. The `findRecord` method will always resolve its promise with the same object for a given type and `id`. The `findRecord` method will always return a **promise** that will be resolved with the record. Example ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id); } }); ``` If the record is not yet available, the store will ask the adapter's `find` method to find the necessary data. If the record is already present in the store, it depends on the reload behavior _when_ the returned promise resolves. ### Reloading The reload behavior is configured either via the passed `options` hash or the result of the adapter's `shouldReloadRecord`. If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if the requested record is already in the store: ```js store.push({ data: { id: 1, type: 'post', revision: 1 } }); // adapter#findRecord resolves with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] store.findRecord('post', 1, { reload: true }).then(function(post) { post.get("revision"); // 2 }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with the cached version in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`, then a background reload is started, which updates the records' data, once it is available: ```js // app/adapters/post.js import ApplicationAdapter from "./application"; export default ApplicationAdapter.extend({ shouldReloadRecord(store, snapshot) { return false; }, shouldBackgroundReloadRecord(store, snapshot) { return true; } }); // ... store.push({ data: { id: 1, type: 'post', revision: 1 } }); var blogPost = store.findRecord('post', 1).then(function(post) { post.get('revision'); // 1 }); // later, once adapter#findRecord resolved with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] blogPost.get('revision'); // 2 ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findRecord`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findRecord: function(store, type, id, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekRecord](#method_peekRecord) to get the cached version of a record. @since 1.13.0 @method findRecord @param {String} modelName @param {(String|Integer)} id @param {Object} options @return {Promise} promise */ findRecord: function (modelName, id, options) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's findRecord method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); (0, _emberDataPrivateDebug.assert)(badIdFormatAssertion, typeof id === 'string' && id.length > 0 || typeof id === 'number' && !isNaN(id)); var internalModel = this._internalModelForId(modelName, id); options = options || {}; if (!this.hasRecordForId(modelName, id)) { return this._findByInternalModel(internalModel, options); } var fetchedInternalModel = this._findRecord(internalModel, options); return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); }, _findRecord: function (internalModel, options) { // Refetch if the reload option is passed if (options.reload) { return this.scheduleFetch(internalModel, options); } var snapshot = internalModel.createSnapshot(options); var typeClass = internalModel.type; var adapter = this.adapterFor(typeClass.modelName); // Refetch the record if the adapter thinks the record is stale if (adapter.shouldReloadRecord(this, snapshot)) { return this.scheduleFetch(internalModel, options); } if (options.backgroundReload === false) { return Promise.resolve(internalModel); } // Trigger the background refetch if backgroundReload option is passed if (options.backgroundReload || adapter.shouldBackgroundReloadRecord(this, snapshot)) { this.scheduleFetch(internalModel, options); } // Return the cached record return Promise.resolve(internalModel); }, _findByInternalModel: function (internalModel, options) { options = options || {}; if (options.preload) { internalModel._preloadData(options.preload); } var fetchedInternalModel = this._findEmptyInternalModel(internalModel, options); return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); }, _findEmptyInternalModel: function (internalModel, options) { if (internalModel.isEmpty()) { return this.scheduleFetch(internalModel, options); } //TODO double check about reloading if (internalModel.isLoading()) { return internalModel._loadingPromise; } return Promise.resolve(internalModel); }, /** 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} modelName @param {Array} ids @return {Promise} promise */ findByIds: function (modelName, ids) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's findByIds method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var promises = new Array(ids.length); for (var i = 0; i < ids.length; i++) { promises[i] = this.findRecord(modelName, ids[i]); } return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(_ember.default.RSVP.all(promises).then(_ember.default.A, null, "DS: Store#findByIds of " + modelName + " complete")); }, /** This method is called by `findRecord` 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 {InternalModel} internalModel model @return {Promise} promise */ // TODO rename this to have an underscore fetchRecord: function (internalModel, options) { var typeClass = internalModel.type; var id = internalModel.id; var adapter = this.adapterFor(typeClass.modelName); (0, _emberDataPrivateDebug.assert)("You tried to find a record but you have no adapter (for " + typeClass + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to find a record but your adapter (for " + typeClass + ") does not implement 'findRecord'", typeof adapter.findRecord === 'function' || typeof adapter.find === 'function'); var promise = (0, _emberDataPrivateSystemStoreFinders._find)(adapter, this, typeClass, id, internalModel, options); return promise; }, scheduleFetchMany: function (records) { var internalModels = new Array(records.length); var fetches = new Array(records.length); for (var i = 0; i < records.length; i++) { internalModels[i] = records[i]._internalModel; } for (var i = 0; i < internalModels.length; i++) { fetches[i] = this.scheduleFetch(internalModels[i]); } return _ember.default.RSVP.Promise.all(fetches); }, scheduleFetch: function (internalModel, options) { var typeClass = internalModel.type; if (internalModel._loadingPromise) { return internalModel._loadingPromise; } var resolver = _ember.default.RSVP.defer('Fetching ' + typeClass + 'with id: ' + internalModel.id); var pendingFetchItem = { record: internalModel, resolver: resolver, options: options }; var promise = resolver.promise; internalModel.loadingData(promise); if (!this._pendingFetch.get(typeClass)) { this._pendingFetch.set(typeClass, [pendingFetchItem]); } else { this._pendingFetch.get(typeClass).push(pendingFetchItem); } _ember.default.run.scheduleOnce('afterRender', this, this.flushAllPendingFetches); return promise; }, flushAllPendingFetches: function () { if (this.isDestroyed || this.isDestroying) { return; } this._pendingFetch.forEach(this._flushPendingFetchForType, this); this._pendingFetch = Map.create(); }, _flushPendingFetchForType: function (pendingFetchItems, typeClass) { var store = this; var adapter = store.adapterFor(typeClass.modelName); var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; var records = _ember.default.A(pendingFetchItems).mapBy('record'); function _fetchRecord(recordResolverPair) { recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record, recordResolverPair.options)); // TODO adapter options } function resolveFoundRecords(records) { records.forEach(function (record) { var pair = _ember.default.A(pendingFetchItems).findBy('record', record); if (pair) { var resolver = pair.resolver; resolver.resolve(record); } }); return records; } function makeMissingRecordsRejector(requestedRecords) { return function rejectMissingRecords(resolvedRecords) { resolvedRecords = _ember.default.A(resolvedRecords); var missingRecords = requestedRecords.reject(function (record) { return resolvedRecords.includes(record); }); if (missingRecords.length) { (0, _emberDataPrivateDebug.warn)('Ember Data expected to find records with the following ids in the adapter response but they were missing: ' + _ember.default.inspect(_ember.default.A(missingRecords).mapBy('id')), false, { id: 'ds.store.missing-records-from-adapter' }); } rejectRecords(missingRecords); }; } function makeRecordsRejector(records) { return function (error) { rejectRecords(records, error); }; } function rejectRecords(records, error) { records.forEach(function (record) { var pair = _ember.default.A(pendingFetchItems).findBy('record', record); if (pair) { var resolver = pair.resolver; resolver.reject(error); } }); } if (pendingFetchItems.length === 1) { _fetchRecord(pendingFetchItems[0]); } else if (shouldCoalesce) { // TODO: Improve records => snapshots => records => snapshots // // We want to provide records to all store methods and snapshots to all // adapter methods. To make sure we're doing that we're providing an array // of snapshots to adapter.groupRecordsForFindMany(), which in turn will // return grouped snapshots instead of grouped records. // // But since the _findMany() finder is a store method we need to get the // records from the grouped snapshots even though the _findMany() finder // will once again convert the records to snapshots for adapter.findMany() var snapshots = _ember.default.A(records).invoke('createSnapshot'); var groups = adapter.groupRecordsForFindMany(this, snapshots); groups.forEach(function (groupOfSnapshots) { var groupOfRecords = _ember.default.A(groupOfSnapshots).mapBy('_internalModel'); var requestedRecords = _ember.default.A(groupOfRecords); var ids = requestedRecords.mapBy('id'); if (ids.length > 1) { (0, _emberDataPrivateSystemStoreFinders._findMany)(adapter, store, typeClass, ids, requestedRecords).then(resolveFoundRecords).then(makeMissingRecordsRejector(requestedRecords)).then(null, makeRecordsRejector(requestedRecords)); } else if (ids.length === 1) { var pair = _ember.default.A(pendingFetchItems).findBy('record', groupOfRecords[0]); _fetchRecord(pair); } else { (0, _emberDataPrivateDebug.assert)("You cannot return an empty array from adapter's method groupRecordsForFindMany", false); } }); } else { pendingFetchItems.forEach(_fetchRecord); } }, /** Get the reference for the specified record. Example ```javascript var userRef = store.getReference('user', 1); // check if the user is loaded var isLoaded = userRef.value() !== null; // get the record of the reference (null if not yet available) var user = userRef.value(); // get the identifier of the reference if (userRef.remoteType() === "id") { var id = userRef.id(); } // load user (via store.find) userRef.load().then(...) // or trigger a reload userRef.reload().then(...) // provide data for reference userRef.push({ id: 1, username: "@user" }).then(function(user) { userRef.value() === user; }); ``` @method getReference @param {String} type @param {String|Integer} id @since 2.5.0 @return {RecordReference} */ getReference: function (type, id) { return this._internalModelForId(type, id).recordReference; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it is available in the store, otherwise it will return `null`. A record is available if it has been fetched earlier, or pushed manually into the store. _Note: This is an synchronous method and does not return a promise._ ```js var post = store.peekRecord('post', 1); post.get('id'); // 1 ``` @since 1.13.0 @method peekRecord @param {String} modelName @param {String|Integer} id @return {DS.Model|null} record */ peekRecord: function (modelName, id) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's peekRecord method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); if (this.hasRecordForId(modelName, id)) { return this._internalModelForId(modelName, id).getRecord(); } 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} internalModel @return {Promise} promise */ reloadRecord: function (internalModel) { var modelName = internalModel.type.modelName; var adapter = this.adapterFor(modelName); var id = internalModel.id; (0, _emberDataPrivateDebug.assert)("You cannot reload a record without an ID", id); (0, _emberDataPrivateDebug.assert)("You tried to reload a record but you have no adapter (for " + modelName + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to reload a record but your adapter does not implement `findRecord`", typeof adapter.findRecord === 'function' || typeof adapter.find === 'function'); return this.scheduleFetch(internalModel); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {(String|DS.Model)} modelName @param {(String|Integer)} inputId @return {Boolean} */ hasRecordForId: function (modelName, inputId) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's hasRecordForId method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var id = (0, _emberDataPrivateSystemCoerceId.default)(inputId); var internalModel = this.typeMapFor(typeClass).idToRecord[id]; return !!internalModel && internalModel.isLoaded(); }, /** 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} modelName @param {(String|Integer)} id @return {DS.Model} record */ recordForId: function (modelName, id) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's recordForId method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); return this._internalModelForId(modelName, id).getRecord(); }, _internalModelForId: function (typeName, inputId) { var typeClass = this.modelFor(typeName); var id = (0, _emberDataPrivateSystemCoerceId.default)(inputId); var idToRecord = this.typeMapFor(typeClass).idToRecord; var record = idToRecord[id]; if (!record || !idToRecord[id]) { record = this.buildInternalModel(typeClass, id); } return record; }, /** @method findMany @private @param {Array} internalModels @return {Promise} promise */ findMany: function (internalModels) { var finds = new Array(internalModels.length); for (var i = 0; i < internalModels.length; i++) { finds[i] = this._findByInternalModel(internalModels[i]); } return Promise.all(finds); }, /** 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 {(Relationship)} relationship @return {Promise} promise */ findHasMany: function (owner, link, relationship) { var adapter = this.adapterFor(owner.type.modelName); (0, _emberDataPrivateDebug.assert)("You tried to load a hasMany relationship but you have no adapter (for " + owner.type + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", typeof adapter.findHasMany === 'function'); return (0, _emberDataPrivateSystemStoreFinders._findHasMany)(adapter, this, owner, link, relationship); }, /** @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.type.modelName); (0, _emberDataPrivateDebug.assert)("You tried to load a belongsTo relationship but you have no adapter (for " + owner.type + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", typeof adapter.findBelongsTo === 'function'); return (0, _emberDataPrivateSystemStoreFinders._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. --- If you do something like this: ```javascript store.query('person', { page: 1 }); ``` The call made to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?page=1" Processing by Api::V1::PersonsController#index as HTML Parameters: { "page"=>"1" } ``` --- If you do something like this: ```javascript store.query('person', { ids: [1, 2, 3] }); ``` The call to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3" Processing by Api::V1::PersonsController#index as HTML Parameters: { "ids" => ["1", "2", "3"] } ``` This method returns a promise, which is resolved with a `RecordArray` once the server returns. @since 1.13.0 @method query @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ query: function (modelName, query) { return this._query(modelName, query); }, _query: function (modelName, query, array) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's query method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)("You need to pass a query hash to the store's query method", query); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); array = array || this.recordArrayManager.createAdapterPopulatedRecordArray(typeClass, query); var adapter = this.adapterFor(modelName); (0, _emberDataPrivateDebug.assert)("You tried to load a query but you have no adapter (for " + typeClass + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to load a query but your adapter does not implement `query`", typeof adapter.query === 'function'); return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._query)(adapter, this, typeClass, query, array)); }, /** This method makes a request for one record, where the `id` is not known beforehand (if the `id` is known, use `findRecord` instead). This method can be used when it is certain that the server will return a single object for the primary data. Let's assume our API provides an endpoint for the currently logged in user via: ``` // GET /api/current_user { user: { id: 1234, username: 'admin' } } ``` Since the specific `id` of the `user` is not known beforehand, we can use `queryRecord` to get the user: ```javascript store.queryRecord('user', {}).then(function(user) { let username = user.get('username'); console.log(`Currently logged in as ${username}`); }); ``` The request is made through the adapters' `queryRecord`: ```javascript // app/adapters/user.js import DS from "ember-data"; export default DS.Adapter.extend({ queryRecord(modelName, query) { return Ember.$.getJSON("/api/current_user"); } }); ``` Note: the primary use case for `store.queryRecord` is when a single record is queried and the `id` is not known beforehand. In all other cases `store.query` and using the first item of the array is likely the preferred way: ``` // GET /users?username=unique { data: [{ id: 1234, type: 'user', attributes: { username: "unique" } }] } ``` ```javascript store.query('user', { username: 'unique' }).then(function(users) { return users.get('firstObject'); }).then(function(user) { let id = user.get('id'); }); ``` This method returns a promise, which resolves with the found record. If the adapter returns no data for the primary data of the payload, then `queryRecord` resolves with `null`: ``` // GET /users?username=unique { data: null } ``` ```javascript store.queryRecord('user', { username: 'unique' }).then(function(user) { console.log(user); // null }); ``` @since 1.13.0 @method queryRecord @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise which resolves with the found record or `null` */ queryRecord: function (modelName, query) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's queryRecord method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)("You need to pass a query hash to the store's queryRecord method", query); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var adapter = this.adapterFor(modelName); (0, _emberDataPrivateDebug.assert)("You tried to make a query but you have no adapter (for " + typeClass + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to make a query but your adapter does not implement `queryRecord`", typeof adapter.queryRecord === 'function'); return (0, _emberDataPrivateSystemPromiseProxies.promiseObject)((0, _emberDataPrivateSystemStoreFinders._queryRecord)(adapter, this, typeClass, query)); }, /** `findAll` asks the adapter's `findAll` method to find the records for the given type, and returns a promise which will resolve with all records of this type present in the store, even if the adapter only returns a subset of them. ```app/routes/authors.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findAll('author'); } }); ``` _When_ the returned promise resolves depends on the reload behavior, configured via the passed `options` hash and the result of the adapter's `shouldReloadAll` method. ### Reloading If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if there are already records in the store: ```js store.push({ data: { id: 'first', type: 'author' } }); // adapter#findAll resolves with // [ // { // id: 'second', // type: 'author' // } // ] store.findAll('author', { reload: true }).then(function(authors) { authors.getEach("id"); // ['first', 'second'] }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with all the records currently loaded in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`, then a background reload is started. Once this resolves, the array with which the promise resolves, is updated automatically so it contains all the records in the store: ```js // app/adapters/application.js export default DS.Adapter.extend({ shouldReloadAll(store, snapshotsArray) { return false; }, shouldBackgroundReloadAll(store, snapshotsArray) { return true; } }); // ... store.push({ data: { id: 'first', type: 'author' } }); var allAuthors; store.findAll('author').then(function(authors) { authors.getEach('id'); // ['first'] allAuthors = authors; }); // later, once adapter#findAll resolved with // [ // { // id: 'second', // type: 'author' // } // ] allAuthors.getEach('id'); // ['first', 'second'] ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findAll`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.findAll('post', { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the `snapshotRecordArray` ```app/routes/posts.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findAll('post', { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findAll: function(store, type, sinceToken, snapshotRecordArray) { if (snapshotRecordArray.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekAll](#method_peekAll) to get an array of current records in the store, without waiting until a reload is finished. See [query](#method_query) to only get a subset of records from the server. @since 1.13.0 @method findAll @param {String} modelName @param {Object} options @return {Promise} promise */ findAll: function (modelName, options) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's findAll method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); return this._fetchAll(typeClass, this.peekAll(modelName), options); }, /** @method _fetchAll @private @param {DS.Model} typeClass @param {DS.RecordArray} array @return {Promise} promise */ _fetchAll: function (typeClass, array, options) { options = options || {}; var adapter = this.adapterFor(typeClass.modelName); var sinceToken = this.typeMapFor(typeClass).metadata.since; (0, _emberDataPrivateDebug.assert)("You tried to load all records but you have no adapter (for " + typeClass + ")", adapter); (0, _emberDataPrivateDebug.assert)("You tried to load all records but your adapter does not implement `findAll`", typeof adapter.findAll === 'function'); if (options.reload) { set(array, 'isUpdating', true); return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options)); } var snapshotArray = array.createSnapshot(options); if (adapter.shouldReloadAll(this, snapshotArray)) { set(array, 'isUpdating', true); return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options)); } if (options.backgroundReload === false) { return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(Promise.resolve(array)); } if (options.backgroundReload || adapter.shouldBackgroundReloadAll(this, snapshotArray)) { set(array, 'isUpdating', true); (0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options); } return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(Promise.resolve(array)); }, /** @method didUpdateAll @param {DS.Model} typeClass @private */ didUpdateAll: function (typeClass) { var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); set(liveRecordArray, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type in the store. Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use [store.findAll](#method_findAll). Also note that multiple calls to `peekAll` for a given type will always return the same `RecordArray`. Example ```javascript var localPosts = store.peekAll('post'); ``` @since 1.13.0 @method peekAll @param {String} modelName @return {DS.RecordArray} */ peekAll: function (modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's peekAll method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); this.recordArrayManager.populateLiveRecordArray(liveRecordArray, typeClass); return liveRecordArray; }, /** This method unloads all records in the store. Optionally you can pass a type which unload all records for a given type. ```javascript store.unloadAll(); store.unloadAll('post'); ``` @method unloadAll @param {String} modelName */ unloadAll: function (modelName) { (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), !modelName || typeof modelName === 'string'); if (arguments.length === 0) { var typeMaps = this.typeMaps; var keys = Object.keys(typeMaps); var types = new Array(keys.length); for (var i = 0; i < keys.length; i++) { types[i] = typeMaps[keys[i]]['type'].modelName; } types.forEach(this.unloadAll, this); } else { var typeClass = this.modelFor(modelName); var typeMap = this.typeMapFor(typeClass); var records = typeMap.records.slice(); var record = undefined; for (var i = 0; i < records.length; i++) { record = records[i]; record.unloadRecord(); record.destroy(); // maybe within unloadRecord } typeMap.metadata = new _emberDataPrivateSystemEmptyObject.default(); } }, /** 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 filter function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. Example ```javascript store.filter('post', function(post) { return post.get('unread'); }); ``` 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 is the equivalent of calling [query](#method_query) with that same query, to fetch additional records from the server. The results returned by the server could then appear in the filter if they match the filter function. The query itself is not used to filter records, it's only sent to your server for you to be able to do server-side filtering. The filter function will be applied on the returned results regardless. 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 @private @param {String} modelName @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} @deprecated */ filter: function (modelName, query, filter) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's filter method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); if (!_ember.default.ENV.ENABLE_DS_FILTER) { (0, _emberDataPrivateDebug.assert)('The filter API has been moved to a plugin. To enable store.filter using an environment flag, or to use an alternative, you can visit the ember-data-filter addon page. https://github.com/ember-data/ember-data-filter', false); } var promise; var length = arguments.length; var array; var hasQuery = length === 3; // allow an optional server query if (hasQuery) { promise = this.query(modelName, query); } else if (arguments.length === 2) { filter = query; } modelName = this.modelFor(modelName); if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(modelName, filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(modelName, filter); } promise = promise || Promise.resolve(array); return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(promise.then(function () { return array; }, null, 'DS: Store#filter of ' + modelName)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a findRecord() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded('post', 1); // false store.findRecord('post', 1).then(function() { store.recordIsLoaded('post', 1); // true }); ``` @method recordIsLoaded @param {String} modelName @param {string} id @return {boolean} */ recordIsLoaded: function (modelName, id) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's recordIsLoaded method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); return this.hasRecordForId(modelName, id); }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes 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 {InternalModel} internalModel */ dataWasUpdated: function (type, internalModel) { this.recordArrayManager.recordDidChange(internalModel); }, // .............. // . 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 {InternalModel} internalModel @param {Resolver} resolver @param {Object} options */ scheduleSave: function (internalModel, resolver, options) { var snapshot = internalModel.createSnapshot(options); internalModel.flushChangedAttributes(); internalModel.adapterWillCommit(); this._pendingSave.push({ snapshot: snapshot, resolver: 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 _this = this; var pending = this._pendingSave.slice(); this._pendingSave = []; pending.forEach(function (pendingItem) { var snapshot = pendingItem.snapshot; var resolver = pendingItem.resolver; var record = snapshot._internalModel; var adapter = _this.adapterFor(record.type.modelName); var operation; if (get(record, 'currentState.stateName') === 'root.deleted.saved') { return resolver.resolve(); } else if (record.isNew()) { operation = 'createRecord'; } else if (record.isDeleted()) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, _this, operation, snapshot)); }); }, /** 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 {InternalModel} internalModel the in-flight internal model @param {Object} data optional data (see above) */ didSaveRecord: function (internalModel, dataArg) { var data; if (dataArg) { data = dataArg.data; } if (data) { // normalize relationship IDs into records this._backburner.schedule('normalizeRelationships', this, '_setupRelationships', internalModel, data); this.updateId(internalModel, data); } //We first make sure the primary data has been updated //TODO try to move notification to the user to the end of the runloop internalModel.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 {InternalModel} internalModel @param {Object} errors */ recordWasInvalid: function (internalModel, errors) { internalModel.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 {InternalModel} internalModel @param {Error} error */ recordWasError: function (internalModel, error) { internalModel.adapterDidError(error); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {InternalModel} internalModel @param {Object} data */ updateId: function (internalModel, data) { var oldId = internalModel.id; var id = (0, _emberDataPrivateSystemCoerceId.default)(data.id); (0, _emberDataPrivateDebug.assert)("An adapter cannot assign a new id to a record that already has an id. " + internalModel + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); this.typeMapFor(internalModel.type).idToRecord[id] = internalModel; internalModel.setId(id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param {DS.Model} typeClass @return {Object} typeMap */ typeMapFor: function (typeClass) { var typeMaps = get(this, 'typeMaps'); var guid = _ember.default.guidFor(typeClass); var typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: new _emberDataPrivateSystemEmptyObject.default(), records: [], metadata: new _emberDataPrivateSystemEmptyObject.default(), type: typeClass }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {(String|DS.Model)} type @param {Object} data */ _load: function (data) { var internalModel = this._internalModelForId(data.type, data.id); internalModel.setupData(data); this.recordArrayManager.recordDidChange(internalModel); return internalModel; }, /* In case someone defined a relationship to a mixin, for example: ``` var Comment = DS.Model.extend({ owner: belongsTo('commentable'. { polymorphic: true}) }); var Commentable = Ember.Mixin.create({ comments: hasMany('comment') }); ``` we want to look up a Commentable class which has all the necessary relationship metadata. Thus, we look up the mixin and create a mock DS.Model, so we can access the relationship CPs of the mixin (`comments`) in this case */ _modelForMixin: function (modelName) { var normalizedModelName = (0, _emberDataPrivateSystemNormalizeModelName.default)(modelName); // container.registry = 2.1 // container._registry = 1.11 - 2.0 // container = < 1.11 var owner = (0, _emberDataPrivateUtils.getOwner)(this); var mixin = owner._lookupFactory('mixin:' + normalizedModelName); if (mixin) { //Cache the class as a model owner.register('model:' + normalizedModelName, _emberDataModel.default.extend(mixin)); } var factory = this.modelFactoryFor(normalizedModelName); if (factory) { factory.__isMixin = true; factory.__mixin = mixin; } return factory; }, /** Returns the model class for the particular `modelName`. The class of a model might be useful if you want to get a list of all the relationship names of the model, see [`relationshipNames`](http://emberjs.com/api/data/classes/DS.Model.html#property_relationshipNames) for example. @method modelFor @param {String} modelName @return {DS.Model} */ modelFor: function (modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's modelFor method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var factory = this.modelFactoryFor(modelName); if (!factory) { //Support looking up mixins as base types for polymorphic relationships factory = this._modelForMixin(modelName); } if (!factory) { throw new _ember.default.Error("No model was found for '" + modelName + "'"); } factory.modelName = factory.modelName || (0, _emberDataPrivateSystemNormalizeModelName.default)(modelName); return factory; }, modelFactoryFor: function (modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's modelFactoryFor method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var normalizedKey = (0, _emberDataPrivateSystemNormalizeModelName.default)(modelName); var owner = (0, _emberDataPrivateUtils.getOwner)(this); return owner._lookupFactory('model:' + normalizedKey); }, /** Push some data for a given type into the store. This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments: - record's `type` should always be in singular, dasherized form - members (properties) should be camelCased [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level): ```js store.push({ data: { // primary data for single record of type `Person` id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } } }); ``` [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7) `data` property can also hold an array (of records): ```js store.push({ data: [ // an array of records { id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } }, { id: '2', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' } } ] }); ``` [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355) There are some typical properties for `JSONAPI` payload: * `id` - mandatory, unique record's key * `type` - mandatory string which matches `model`'s dasherized name in singular form * `attributes` - object which holds data for record attributes - `DS.attr`'s declared in model * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`): - [`links`](http://jsonapi.org/format/#document-links) - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship For this model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { data: [ { id: '2', type: 'person' }, { id: '3', type: 'person' }, { id: '4', type: 'person' } ] } } } } ``` [Demo.](http://ember-twiddle.com/343e1735e034091f5bde) To represent the children relationship as a URL: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { links: { related: '/people/1/children' } } } } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's [normalize](#method_normalize) method is a convenience helper for converting a json payload into the form Ember Data expects. ```js store.push(store.normalize('person', data)); ``` This method can be used both to push in brand new records, as well as to update existing records. @method push @param {Object} data @return {DS.Model|Array} the record(s) that was created or updated. */ push: function (data) { var included = data.included; var i, length; if (included) { for (i = 0, length = included.length; i < length; i++) { this._pushInternalModel(included[i]); } } if (Array.isArray(data.data)) { length = data.data.length; var internalModels = new Array(length); for (i = 0; i < length; i++) { internalModels[i] = this._pushInternalModel(data.data[i]).getRecord(); } return internalModels; } if (data.data === null) { return null; } (0, _emberDataPrivateDebug.assert)('Expected an object in the \'data\' property in a call to \'push\' for ' + data.type + ', but was ' + _ember.default.typeOf(data.data), _ember.default.typeOf(data.data) === 'object'); var internalModel = this._pushInternalModel(data.data); return internalModel.getRecord(); }, _hasModelFor: function (type) { return !!(0, _emberDataPrivateUtils.getOwner)(this)._lookupFactory('model:' + type); }, _pushInternalModel: function (data) { var _this2 = this; var modelName = data.type; (0, _emberDataPrivateDebug.assert)('You must include an \'id\' for ' + modelName + ' in an object passed to \'push\'', data.id !== null && data.id !== undefined && data.id !== ''); (0, _emberDataPrivateDebug.assert)('You tried to push data with a type \'' + modelName + '\' but no model could be found with that name.', this._hasModelFor(modelName)); (0, _emberDataPrivateDebug.runInDebug)(function () { // If Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload // contains unknown attributes or relationships, log a warning. if (_ember.default.ENV.DS_WARN_ON_UNKNOWN_KEYS) { (function () { var type = _this2.modelFor(modelName); // Check unknown attributes var unknownAttributes = Object.keys(data.attributes || {}).filter(function (key) { return !get(type, 'fields').has(key); }); var unknownAttributesMessage = 'The payload for \'' + type.modelName + '\' contains these unknown attributes: ' + unknownAttributes + '. Make sure they\'ve been defined in your model.'; (0, _emberDataPrivateDebug.warn)(unknownAttributesMessage, unknownAttributes.length === 0, { id: 'ds.store.unknown-keys-in-payload' }); // Check unknown relationships var unknownRelationships = Object.keys(data.relationships || {}).filter(function (key) { return !get(type, 'fields').has(key); }); var unknownRelationshipsMessage = 'The payload for \'' + type.modelName + '\' contains these unknown relationships: ' + unknownRelationships + '. Make sure they\'ve been defined in your model.'; (0, _emberDataPrivateDebug.warn)(unknownRelationshipsMessage, unknownRelationships.length === 0, { id: 'ds.store.unknown-keys-in-payload' }); })(); } }); // Actually load the record into the store. var internalModel = this._load(data); this._backburner.join(function () { _this2._backburner.schedule('normalizeRelationships', _this2, '_setupRelationships', internalModel, data); }); return internalModel; }, _setupRelationships: function (record, data) { // This will convert relationships specified as IDs into DS.Model instances // (possibly unloaded) and also create the data structures used to track // relationships. setupRelationships(this, record, data); }, /** 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. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```js 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). Alternatively, `pushPayload` will accept a model type which will determine which serializer will process the payload. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer; ``` ```js store.pushPayload('comment', pushData); // Will use the application serializer store.pushPayload('post', pushData); // Will use the post serializer ``` @method pushPayload @param {String} modelName Optionally, a model type used to determine which serializer will be used @param {Object} inputPayload */ pushPayload: function (modelName, inputPayload) { var _this3 = this; var serializer; var payload; if (!inputPayload) { payload = modelName; serializer = defaultSerializer(this); (0, _emberDataPrivateDebug.assert)("You cannot use `store#pushPayload` without a modelName unless your default serializer defines `pushPayload`", typeof serializer.pushPayload === 'function'); } else { payload = inputPayload; (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); serializer = this.serializerFor(modelName); } if ((0, _emberDataPrivateFeatures.default)('ds-pushpayload-return')) { return this._adapterRun(function () { return serializer.pushPayload(_this3, payload); }); } else { this._adapterRun(function () { return serializer.pushPayload(_this3, payload); }); } }, /** `normalize` converts a json payload into the normalized form that [push](#method_push) expects. Example ```js socket.on('message', function(message) { var modelName = message.model; var data = message.data; store.push(store.normalize(modelName, data)); }); ``` @method normalize @param {String} modelName The name of the model type for this payload @param {Object} payload @return {Object} The normalized payload */ normalize: function (modelName, payload) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's normalize method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var serializer = this.serializerFor(modelName); var model = this.modelFor(modelName); return serializer.normalize(model, payload); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {DS.Model} type @param {String} id @param {Object} data @return {InternalModel} internal model */ buildInternalModel: function (type, id, data) { var typeMap = this.typeMapFor(type); var idToRecord = typeMap.idToRecord; (0, _emberDataPrivateDebug.assert)('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]); (0, _emberDataPrivateDebug.assert)('\'' + _ember.default.inspect(type) + '\' does not appear to be an ember-data model', typeof type._create === 'function'); // lookupFactory should really return an object that creates // instances with the injections applied var internalModel = new _emberDataPrivateSystemModelInternalModel.default(type, id, this, null, data); // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = internalModel; } typeMap.records.push(internalModel); return internalModel; }, //Called by the state machine to notify the store that the record is ready to be interacted with recordWasLoaded: function (record) { this.recordArrayManager.recordWasLoaded(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 {InternalModel} internalModel */ _dematerializeRecord: function (internalModel) { var type = internalModel.type; var typeMap = this.typeMapFor(type); var id = internalModel.id; internalModel.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = typeMap.records.indexOf(internalModel); typeMap.records.splice(loc, 1); }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns an instance of the adapter for a given type. For example, `adapterFor('person')` will return an instance of `App.PersonAdapter`. If no `App.PersonAdapter` is found, this method will look for an `App.ApplicationAdapter` (the default adapter for your entire application). If no `App.ApplicationAdapter` is found, it will return the value of the `defaultAdapter`. @method adapterFor @public @param {String} modelName @return DS.Adapter */ adapterFor: function (modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's adapterFor method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); return this.lookupAdapter(modelName); }, _adapterRun: function (fn) { return this._backburner.run(fn); }, // .............................. // . 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 attempt to get the `defaultSerializer` from the `PersonAdapter` (`adapterFor('person')`). If a serializer cannot be found on the adapter, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @public @param {String} modelName the record to serialize @return {DS.Serializer} */ serializerFor: function (modelName) { (0, _emberDataPrivateDebug.assert)("You need to pass a model name to the store's serializerFor method", isPresent(modelName)); (0, _emberDataPrivateDebug.assert)('Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ' + _ember.default.inspect(modelName), typeof modelName === 'string'); var fallbacks = ['application', this.adapterFor(modelName).get('defaultSerializer'), '-default']; var serializer = this.lookupSerializer(modelName, fallbacks); return serializer; }, /** Retrieve a particular instance from the container cache. If not found, creates it and placing it in the cache. Enabled a store to manage local instances of adapters and serializers. @method retrieveManagedInstance @private @param {String} modelName the object modelName @param {String} name the object name @param {Array} fallbacks the fallback objects to lookup if the lookup for modelName or 'application' fails @return {Ember.Object} */ retrieveManagedInstance: function (type, modelName, fallbacks) { var normalizedModelName = (0, _emberDataPrivateSystemNormalizeModelName.default)(modelName); var instance = this._instanceCache.get(type, normalizedModelName, fallbacks); set(instance, 'store', this); return instance; }, lookupAdapter: function (name) { return this.retrieveManagedInstance('adapter', name, this.get('_adapterFallbacks')); }, _adapterFallbacks: _ember.default.computed('adapter', function () { var adapter = this.get('adapter'); return ['application', adapter, '-json-api']; }), lookupSerializer: function (name, fallbacks) { return this.retrieveManagedInstance('serializer', name, fallbacks); }, willDestroy: function () { this._super.apply(this, arguments); this.recordArrayManager.destroy(); this.unloadAll(); } }); function deserializeRecordId(store, key, relationship, id) { if (isNone(id)) { return; } (0, _emberDataPrivateDebug.assert)('A ' + relationship.parentType + ' record was pushed into the store with the value of ' + key + ' being ' + _ember.default.inspect(id) + ', but ' + key + ' is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.', !Array.isArray(id)); //TODO:Better asserts return store._internalModelForId(id.type, id.id); } function deserializeRecordIds(store, key, relationship, ids) { if (isNone(ids)) { return; } (0, _emberDataPrivateDebug.assert)('A ' + relationship.parentType + ' record was pushed into the store with the value of ' + key + ' being \'' + _ember.default.inspect(ids) + '\', but ' + key + ' is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.', Array.isArray(ids)); var _ids = new Array(ids.length); for (var i = 0; i < ids.length; i++) { _ids[i] = deserializeRecordId(store, key, relationship, ids[i]); } return _ids; } // Delegation to the adapter and promise management function defaultSerializer(store) { return store.serializerFor('application'); } function _commit(adapter, store, operation, snapshot) { var internalModel = snapshot._internalModel; var modelName = snapshot.modelName; var typeClass = store.modelFor(modelName); var promise = adapter[operation](store, typeClass, snapshot); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = 'DS: Extract and notify about ' + operation + ' completion of ' + internalModel; (0, _emberDataPrivateDebug.assert)('Your adapter\'s \'' + operation + '\' method must return a value, but it returned \'undefined\'', promise !== undefined); promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { store._adapterRun(function () { var payload, data; if (adapterPayload) { payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, snapshot.id, operation); if (payload.included) { store.push({ data: payload.included }); } data = payload.data; } store.didSaveRecord(internalModel, { data: data }); }); return internalModel; }, function (error) { if (error instanceof _emberDataAdaptersErrors.InvalidError) { var errors = serializer.extractErrors(store, typeClass, error, snapshot.id); store.recordWasInvalid(internalModel, errors); } else { store.recordWasError(internalModel, error); } throw error; }, label); } function setupRelationships(store, record, data) { if (!data.relationships) { return; } record.type.eachRelationship(function (key, descriptor) { var kind = descriptor.kind; if (!data.relationships[key]) { return; } var relationship; if (data.relationships[key].links && data.relationships[key].links.related) { var relatedLink = (0, _emberDataPrivateSystemNormalizeLink.default)(data.relationships[key].links.related); if (relatedLink && relatedLink.href) { relationship = record._relationships.get(key); relationship.updateLink(relatedLink.href); } } if (data.relationships[key].meta) { relationship = record._relationships.get(key); relationship.updateMeta(data.relationships[key].meta); } // If the data contains a relationship that is specified as an ID (or IDs), // normalizeRelationship will convert them into DS.Model instances // (possibly unloaded) before we push the payload into the store. normalizeRelationship(store, key, descriptor, data.relationships[key]); var value = data.relationships[key].data; if (value !== undefined) { if (kind === 'belongsTo') { relationship = record._relationships.get(key); relationship.setCanonicalRecord(value); } else if (kind === 'hasMany') { relationship = record._relationships.get(key); relationship.updateRecordsFromAdapter(value); } } }); } function normalizeRelationship(store, key, relationship, jsonPayload) { var data = jsonPayload.data; if (data) { var kind = relationship.kind; if (kind === 'belongsTo') { jsonPayload.data = deserializeRecordId(store, key, relationship, data); } else if (kind === 'hasMany') { jsonPayload.data = deserializeRecordIds(store, key, relationship, data); } } } exports.Store = Store; exports.default = Store; }); /** @module ember-data */ define('ember-data/-private/system/store/common', ['exports', 'ember'], function (exports, _ember) { exports._bind = _bind; exports._guard = _guard; exports._objectIsAlive = _objectIsAlive; var get = _ember.default.get; function _bind(fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply(undefined, args); }; } function _guard(promise, test) { var guarded = promise['finally'](function () { if (!test()) { guarded._subscribers.length = 0; } }); return guarded; } function _objectIsAlive(object) { return !(get(object, "isDestroyed") || get(object, "isDestroying")); } }); define('ember-data/-private/system/store/container-instance-cache', ['exports', 'ember', 'ember-data/-private/system/empty-object'], function (exports, _ember, _emberDataPrivateSystemEmptyObject) { exports.default = ContainerInstanceCache; var assign = _ember.default.assign || _ember.default.merge; /* * The `ContainerInstanceCache` serves as a lazy cache for looking up * instances of serializers and adapters. It has some additional logic for * finding the 'fallback' adapter or serializer. * * The 'fallback' adapter or serializer is an adapter or serializer that is looked up * when the preferred lookup fails. For example, say you try to look up `adapter:post`, * but there is no entry (app/adapters/post.js in EmberCLI) for `adapter:post` in the registry. * * The `fallbacks` array passed will then be used; the first entry in the fallbacks array * that exists in the container will then be cached for `adapter:post`. So, the next time you * look up `adapter:post`, you'll get the `adapter:application` instance (or whatever the fallback * was if `adapter:application` doesn't exist). * * @private * @class ContainerInstanceCache * */ function ContainerInstanceCache(owner) { this._owner = owner; this._cache = new _emberDataPrivateSystemEmptyObject.default(); } ContainerInstanceCache.prototype = new _emberDataPrivateSystemEmptyObject.default(); assign(ContainerInstanceCache.prototype, { get: function (type, preferredKey, fallbacks) { var cache = this._cache; var preferredLookupKey = type + ':' + preferredKey; if (!(preferredLookupKey in cache)) { var instance = this.instanceFor(preferredLookupKey) || this._findInstance(type, fallbacks); if (instance) { cache[preferredLookupKey] = instance; } } return cache[preferredLookupKey]; }, _findInstance: function (type, fallbacks) { for (var i = 0, _length = fallbacks.length; i < _length; i++) { var fallback = fallbacks[i]; var lookupKey = type + ':' + fallback; var instance = this.instanceFor(lookupKey); if (instance) { return instance; } } }, instanceFor: function (key) { var cache = this._cache; if (!cache[key]) { var instance = this._owner.lookup(key); if (instance) { cache[key] = instance; } } return cache[key]; }, destroy: function () { var cache = this._cache; var cacheEntries = Object.keys(cache); for (var i = 0, _length2 = cacheEntries.length; i < _length2; i++) { var cacheKey = cacheEntries[i]; var cacheEntry = cache[cacheKey]; if (cacheEntry) { cacheEntry.destroy(); } } this._owner = null; }, constructor: ContainerInstanceCache, toString: function () { return 'ContainerInstanceCache'; } }); }); define("ember-data/-private/system/store/finders", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/store/common", "ember-data/-private/system/store/serializer-response", "ember-data/-private/system/store/serializers"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemStoreCommon, _emberDataPrivateSystemStoreSerializerResponse, _emberDataPrivateSystemStoreSerializers) { exports._find = _find; exports._findMany = _findMany; exports._findHasMany = _findHasMany; exports._findBelongsTo = _findBelongsTo; exports._findAll = _findAll; exports._query = _query; exports._queryRecord = _queryRecord; var Promise = _ember.default.RSVP.Promise; function payloadIsNotBlank(adapterPayload) { if (Array.isArray(adapterPayload)) { return true; } else { return Object.keys(adapterPayload || {}).length; } } function _find(adapter, store, typeClass, id, internalModel, options) { var snapshot = internalModel.createSnapshot(options); var promise = adapter.findRecord(store, typeClass, id, snapshot); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, internalModel.type.modelName); var label = "DS: Handle Adapter#findRecord of " + typeClass + " with id: " + id; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { (0, _emberDataPrivateDebug.assert)("You made a `findRecord` request for a " + typeClass.modelName + " with id " + id + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, id, 'findRecord'); (0, _emberDataPrivateDebug.assert)('Ember Data expected the primary data returned from a `findRecord` response to be an object but instead it found an array.', !Array.isArray(payload.data)); //TODO Optimize var record = store.push(payload); return record._internalModel; }); }, function (error) { internalModel.notFound(); if (internalModel.isEmpty()) { internalModel.unloadRecord(); } throw error; }, "DS: Extract payload of '" + typeClass + "'"); } function _findMany(adapter, store, typeClass, ids, internalModels) { var snapshots = _ember.default.A(internalModels).invoke('createSnapshot'); var promise = adapter.findMany(store, typeClass, ids, snapshots); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, typeClass.modelName); var label = "DS: Handle Adapter#findMany of " + typeClass; if (promise === undefined) { throw new Error('adapter.findMany returned undefined, this was very likely a mistake'); } promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { (0, _emberDataPrivateDebug.assert)("You made a `findMany` request for " + typeClass.modelName + " records with ids " + ids + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findMany'); //TODO Optimize, no need to materialize here var records = store.push(payload); var internalModels = new Array(records.length); for (var i = 0; i < records.length; i++) { internalModels[i] = records[i]._internalModel; } return internalModels; }); }, null, "DS: Extract payload of " + typeClass); } function _findHasMany(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var typeClass = store.modelFor(relationship.type); var promise = adapter.findHasMany(store, snapshot, link, relationship); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, relationship.type); var label = "DS: Handle Adapter#findHasMany of " + internalModel + " : " + relationship.type; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { (0, _emberDataPrivateDebug.assert)("You made a `findHasMany` request for a " + internalModel.modelName + "'s `" + relationship.key + "` relationship, using link " + link + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findHasMany'); //TODO Use a non record creating push var records = store.push(payload); var recordArray = records.map(function (record) { return record._internalModel; }); recordArray.meta = payload.meta; return recordArray; }); }, null, "DS: Extract payload of " + internalModel + " : hasMany " + relationship.type); } function _findBelongsTo(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var typeClass = store.modelFor(relationship.type); var promise = adapter.findBelongsTo(store, snapshot, link, relationship); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, relationship.type); var label = "DS: Handle Adapter#findBelongsTo of " + internalModel + " : " + relationship.type; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findBelongsTo'); if (!payload.data) { return null; } //TODO Optimize var record = store.push(payload); return record._internalModel; }); }, null, "DS: Extract payload of " + internalModel + " : " + relationship.type); } function _findAll(adapter, store, typeClass, sinceToken, options) { var modelName = typeClass.modelName; var recordArray = store.peekAll(modelName); var snapshotArray = recordArray.createSnapshot(options); var promise = adapter.findAll(store, typeClass, sinceToken, snapshotArray); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = "DS: Handle Adapter#findAll of " + typeClass; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { (0, _emberDataPrivateDebug.assert)("You made a `findAll` request for " + typeClass.modelName + " records, but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findAll'); //TODO Optimize store.push(payload); }); store.didUpdateAll(typeClass); return store.peekAll(modelName); }, null, "DS: Extract payload of findAll " + typeClass); } function _query(adapter, store, typeClass, query, recordArray) { var modelName = typeClass.modelName; var promise = adapter.query(store, typeClass, query, recordArray); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = "DS: Handle Adapter#query of " + typeClass; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { var records, payload; store._adapterRun(function () { payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'query'); //TODO Optimize records = store.push(payload); }); (0, _emberDataPrivateDebug.assert)('The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use `store.queryRecord` to query for a single record.', Array.isArray(records)); recordArray.loadRecords(records, payload); return recordArray; }, null, "DS: Extract payload of query " + typeClass); } function _queryRecord(adapter, store, typeClass, query) { var modelName = typeClass.modelName; var promise = adapter.queryRecord(store, typeClass, query); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = "DS: Handle Adapter#queryRecord of " + typeClass; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { var record; store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'queryRecord'); (0, _emberDataPrivateDebug.assert)("Expected the primary data returned by the serializer for a `queryRecord` response to be a single object or null but instead it was an array.", !Array.isArray(payload.data), { id: 'ds.store.queryRecord-array-response' }); //TODO Optimize record = store.push(payload); }); return record; }, null, "DS: Extract payload of queryRecord " + typeClass); } }); define('ember-data/-private/system/store/serializer-response', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { exports.validateDocumentStructure = validateDocumentStructure; exports.normalizeResponseHelper = normalizeResponseHelper; /* This is a helper method that validates a JSON API top-level document The format of a document is described here: http://jsonapi.org/format/#document-top-level @method validateDocumentStructure @param {Object} doc JSON API document @return {array} An array of errors found in the document structure */ function validateDocumentStructure(doc) { var errors = []; if (!doc || typeof doc !== 'object') { errors.push('Top level of a JSON API document must be an object'); } else { if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) { errors.push('One or more of the following keys must be present: "data", "errors", "meta".'); } else { if ('data' in doc && 'errors' in doc) { errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document'); } } if ('data' in doc) { if (!(doc.data === null || Array.isArray(doc.data) || typeof doc.data === 'object')) { errors.push('data must be null, an object, or an array'); } } if ('meta' in doc) { if (typeof doc.meta !== 'object') { errors.push('meta must be an object'); } } if ('errors' in doc) { if (!Array.isArray(doc.errors)) { errors.push('errors must be an array'); } } if ('links' in doc) { if (typeof doc.links !== 'object') { errors.push('links must be an object'); } } if ('jsonapi' in doc) { if (typeof doc.jsonapi !== 'object') { errors.push('jsonapi must be an object'); } } if ('included' in doc) { if (typeof doc.included !== 'object') { errors.push('included must be an array'); } } } return errors; } /* This is a helper method that always returns a JSON-API Document. @method normalizeResponseHelper @param {DS.Serializer} serializer @param {DS.Store} store @param {subclass of DS.Model} modelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) { var normalizedResponse = serializer.normalizeResponse(store, modelClass, payload, id, requestType); var validationErrors = []; (0, _emberDataPrivateDebug.runInDebug)(function () { validationErrors = validateDocumentStructure(normalizedResponse); }); (0, _emberDataPrivateDebug.assert)('normalizeResponse must return a valid JSON API document:\n\t* ' + validationErrors.join('\n\t* '), _ember.default.isEmpty(validationErrors)); return normalizedResponse; } }); define("ember-data/-private/system/store/serializers", ["exports"], function (exports) { exports.serializerForAdapter = serializerForAdapter; function serializerForAdapter(store, adapter, type) { var serializer = adapter.serializer; if (serializer === undefined) { serializer = store.serializerFor(type); } if (serializer === null || serializer === undefined) { serializer = { extract: function (store, type, payload) { return payload; } }; } return serializer; } }); define("ember-data/-private/transforms", ["exports", "ember-data/transform", "ember-data/-private/transforms/number", "ember-data/-private/transforms/date", "ember-data/-private/transforms/string", "ember-data/-private/transforms/boolean"], function (exports, _emberDataTransform, _emberDataPrivateTransformsNumber, _emberDataPrivateTransformsDate, _emberDataPrivateTransformsString, _emberDataPrivateTransformsBoolean) { exports.Transform = _emberDataTransform.default; exports.NumberTransform = _emberDataPrivateTransformsNumber.default; exports.DateTransform = _emberDataPrivateTransformsDate.default; exports.StringTransform = _emberDataPrivateTransformsString.default; exports.BooleanTransform = _emberDataPrivateTransformsBoolean.default; }); define('ember-data/-private/transforms/boolean', ['exports', 'ember', 'ember-data/transform', 'ember-data/-private/features'], function (exports, _ember, _emberDataTransform, _emberDataPrivateFeatures) { var isNone = _ember.default.isNone; /** 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 ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ isAdmin: DS.attr('boolean'), name: DS.attr('string'), email: DS.attr('string') }); ``` By default the boolean transform only allows for values of `true` or `false`. You can opt into allowing `null` values for boolean attributes via `DS.attr('boolean', { allowNull: true })` ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ email: DS.attr('string'), username: DS.attr('string'), wantsWeeklyEmail: DS.attr('boolean', { allowNull: true }) }); ``` @class BooleanTransform @extends DS.Transform @namespace DS */ exports.default = _emberDataTransform.default.extend({ deserialize: function (serialized, options) { var type = typeof serialized; if (true) { if (isNone(serialized) && options.allowNull === true) { return null; } } 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, options) { if (true) { if (isNone(deserialized) && options.allowNull === true) { return null; } } return Boolean(deserialized); } }); }); define("ember-data/-private/transforms/date", ["exports", "ember-data/-private/ext/date", "ember-data/transform"], function (exports, _emberDataPrivateExtDate, _emberDataTransform) { exports.default = _emberDataTransform.default.extend({ deserialize: function (serialized) { var type = typeof serialized; if (type === "string") { return new Date((0, _emberDataPrivateExtDate.parseDate)(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is null return null // if the value is not present in the data return undefined return serialized; } else { return null; } }, serialize: function (date) { if (date instanceof Date && !isNaN(date)) { return date.toISOString(); } else { return null; } } }); }); /** 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. It uses the [`ISO 8601`](https://en.wikipedia.org/wiki/ISO_8601) standard. ```app/models/score.js import DS from 'ember-data'; export default DS.Model.extend({ value: DS.attr('number'), player: DS.belongsTo('player'), date: DS.attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ define("ember-data/-private/transforms/number", ["exports", "ember", "ember-data/transform"], function (exports, _ember, _emberDataTransform) { var empty = _ember.default.isEmpty; function isNumber(value) { return value === value && value !== Infinity && value !== -Infinity; } /** 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 ```app/models/score.js import DS from 'ember-data'; export default DS.Model.extend({ value: DS.attr('number'), player: DS.belongsTo('player'), date: DS.attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ exports.default = _emberDataTransform.default.extend({ deserialize: function (serialized) { var transformed; if (empty(serialized)) { return null; } else { transformed = Number(serialized); return isNumber(transformed) ? transformed : null; } }, serialize: function (deserialized) { var transformed; if (empty(deserialized)) { return null; } else { transformed = Number(deserialized); return isNumber(transformed) ? transformed : null; } } }); }); define("ember-data/-private/transforms/string", ["exports", "ember", "ember-data/transform"], function (exports, _ember, _emberDataTransform) { var none = _ember.default.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 ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ isAdmin: DS.attr('boolean'), name: DS.attr('string'), email: DS.attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ exports.default = _emberDataTransform.default.extend({ deserialize: function (serialized) { return none(serialized) ? null : String(serialized); }, serialize: function (deserialized) { return none(deserialized) ? null : String(deserialized); } }); }); define('ember-data/-private/utils', ['exports', 'ember'], function (exports, _ember) { var get = _ember.default.get; /* Check if the passed model has a `type` attribute or a relationship named `type`. @method modelHasAttributeOrRelationshipNamedType @param modelClass */ function modelHasAttributeOrRelationshipNamedType(modelClass) { return get(modelClass, 'attributes').has('type') || get(modelClass, 'relationshipsByName').has('type'); } /* ember-container-inject-owner is a new feature in Ember 2.3 that finally provides a public API for looking items up. This function serves as a super simple polyfill to avoid triggering deprecations. */ function getOwner(context) { var owner; if (_ember.default.getOwner) { owner = _ember.default.getOwner(context); } if (!owner && context.container) { owner = context.container; } if (owner && owner.lookupFactory && !owner._lookupFactory) { // `owner` is a container, we are just making this work owner._lookupFactory = owner.lookupFactory; owner.register = function () { var registry = owner.registry || owner._registry || owner; return registry.register.apply(registry, arguments); }; } return owner; } exports.modelHasAttributeOrRelationshipNamedType = modelHasAttributeOrRelationshipNamedType; exports.getOwner = getOwner; }); define('ember-data/-private/utils/parse-response-headers', ['exports', 'ember-data/-private/system/empty-object'], function (exports, _emberDataPrivateSystemEmptyObject) { exports.default = parseResponseHeaders; function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } var CLRF = '\u000d\u000a'; function parseResponseHeaders(headersString) { var headers = new _emberDataPrivateSystemEmptyObject.default(); if (!headersString) { return headers; } var headerPairs = headersString.split(CLRF); headerPairs.forEach(function (header) { var _header$split = header.split(':'); var _header$split2 = _toArray(_header$split); var field = _header$split2[0]; var value = _header$split2.slice(1); field = field.trim(); value = value.join(':').trim(); if (value) { headers[field] = value; } }); return headers; } }); define('ember-data/adapter', ['exports', 'ember'], function (exports, _ember) { var get = _ember.default.get; /** 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` in the `app/adapters` folder: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ // ...your code here }); ``` Model-specific adapters can be created by putting your adapter class in an `app/adapters/` + `model-name` + `.js` file of the application. ```app/adapters/post.js import DS from 'ember-data'; export default DS.Adapter.extend({ // ...Post-specific adapter code goes here }); ``` `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: * `findRecord()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `query()` 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 */ exports.default = _ember.default.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 than a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```app/adapters/django.js import DS from 'ember-data'; export default DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ defaultSerializer: '-default', /** The `findRecord()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `findRecord()` being called, you should query your persistence layer for a record with the given ID. The `findRecord` method should return a promise that will resolve to a JavaScript object that will be normalized by the serializer. Here is an example `findRecord` implementation: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findRecord: function(store, type, id, snapshot) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}/${id}`).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method findRecord @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ findRecord: null, /** The `findAll()` method is used to retrieve all records for a given type. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method findAll @param {DS.Store} store @param {DS.Model} type @param {String} sinceToken @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Promise} promise */ findAll: null, /** This method is called when you call `query` on the store. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ query: function(store, type, query) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method query @param {DS.Store} store @param {DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ query: null, /** The `queryRecord()` method is invoked when the store is asked for a single record through a query object. In response to `queryRecord()` being called, you should always fetch fresh data. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `queryRecord` implementation: Example ```app/adapters/application.js import DS from 'ember-data'; import Ember from 'ember'; export default DS.Adapter.extend(DS.BuildURLMixin, { queryRecord: function(store, type, query) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method queryRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @return {Promise} promise */ queryRecord: 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 import DS from 'ember-data'; import { v4 } from 'uuid'; export default DS.Adapter.extend({ generateIdForRecord: function(store, inputProperties) { return v4(); } }); ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {Object} inputProperties a hash of properties to set on the newly created record. @return {(String|Number)} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var url = `/${type.modelName}`; // ... } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} serialized snapshot */ serialize: function (snapshot, options) { return get(snapshot.record, 'store').serializerFor(snapshot.modelName).serialize(snapshot, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and sends it to the server. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'POST', url: `/${type.modelName}`, 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 {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: null, /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and sends it to the server. The updateRecord method is expected to return a promise that will resolve with the serialized record. This allows the backend to inform the Ember Data store the current state of this record after the update. If it is not possible to return a serialized record the updateRecord promise can also resolve with `undefined` and the Ember Data store will assume all of the updates were successfully applied on the backend. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ updateRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'PUT', url: `/${type.modelName}/${id}`, 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 {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: null, /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ deleteRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'DELETE', url: `/${type.modelName}/${id}`, 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 {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: null, /** By default the store will try to coalesce all `fetchRecord` calls within the same runloop into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. You can opt out of this behaviour by either not implementing the findMany hook or by setting coalesceFindRequests to false. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: true, /** The store will call `findMany` instead of multiple `findRecord` requests to find multiple records at once if coalesceFindRequests is true. ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findMany(store, type, ids, snapshots) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'GET', url: `/${type.modelName}/`, dataType: 'json', data: { filter: { id: ids.join(',') } } }).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 {DS.Model} type the DS.Model class of the records @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: null, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. For example, if your api has nested URLs that depend on the parent, you will want to group records by their parent. The default implementation returns the records as a single group. @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, snapshots) { return [snapshots]; }, /** This method is used by the store to determine if the store should reload a record from the adapter when a record is requested by `store.findRecord`. If this method returns `true`, the store will re-fetch a record from the adapter. If this method returns `false`, the store will resolve immediately using the cached record. For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write: ```javascript shouldReloadRecord: function(store, ticketSnapshot) { var timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt'), 'minutes'); if (timeDiff > 20) { return true; } else { return false; } } ``` This method would ensure that whenever you do `store.findRecord('ticket', id)` you will always get a ticket that is no more than 20 minutes old. In case the cached version is more than 20 minutes old, `findRecord` will not resolve until you fetched the latest version. By default this hook returns `false`, as most UIs should not block user interactions while waiting on data update. Note that, with default settings, `shouldBackgroundReloadRecord` will always re-fetch the records in the background even if `shouldReloadRecord` returns `false`. You can override `shouldBackgroundReloadRecord` if this does not suit your use case. @since 1.13.0 @method shouldReloadRecord @param {DS.Store} store @param {DS.Snapshot} snapshot @return {Boolean} */ shouldReloadRecord: function (store, snapshot) { return false; }, /** This method is used by the store to determine if the store should reload all records from the adapter when records are requested by `store.findAll`. If this method returns `true`, the store will re-fetch all records from the adapter. If this method returns `false`, the store will resolve immediately using the cached records. For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write: ```javascript shouldReloadAll: function(store, snapshotArray) { var snapshots = snapshotArray.snapshots(); return snapshots.any(function(ticketSnapshot) { var timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt'), 'minutes'); if (timeDiff > 20) { return true; } else { return false; } }); } ``` This method would ensure that whenever you do `store.findAll('ticket')` you will always get a list of tickets that are no more than 20 minutes old. In case a cached version is more than 20 minutes old, `findAll` will not resolve until you fetched the latest versions. By default this methods returns `true` if the passed `snapshotRecordArray` is empty (meaning that there are no records locally available yet), otherwise it returns `false`. Note that, with default settings, `shouldBackgroundReloadAll` will always re-fetch all the records in the background even if `shouldReloadAll` returns `false`. You can override `shouldBackgroundReloadAll` if this does not suit your use case. @since 1.13.0 @method shouldReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldReloadAll: function (store, snapshotRecordArray) { return !snapshotRecordArray.length; }, /** This method is used by the store to determine if the store should reload a record after the `store.findRecord` method resolves a cached record. This method is *only* checked by the store when the store is returning a cached record. If this method returns `true` the store will re-fetch a record from the adapter. For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement `shouldBackgroundReloadRecord` as follows: ```javascript shouldBackgroundReloadRecord: function(store, snapshot) { var connection = window.navigator.connection; if (connection === 'cellular' || connection === 'none') { return false; } else { return true; } } ``` By default this hook returns `true` so the data for the record is updated in the background. @since 1.13.0 @method shouldBackgroundReloadRecord @param {DS.Store} store @param {DS.Snapshot} snapshot @return {Boolean} */ shouldBackgroundReloadRecord: function (store, snapshot) { return true; }, /** This method is used by the store to determine if the store should reload a record array after the `store.findAll` method resolves with a cached record array. This method is *only* checked by the store when the store is returning a cached record array. If this method returns `true` the store will re-fetch all records from the adapter. For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement `shouldBackgroundReloadAll` as follows: ```javascript shouldBackgroundReloadAll: function(store, snapshotArray) { var connection = window.navigator.connection; if (connection === 'cellular' || connection === 'none') { return false; } else { return true; } } ``` By default this method returns `true`, indicating that a background reload should always be triggered. @since 1.13.0 @method shouldBackgroundReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldBackgroundReloadAll: function (store, snapshotRecordArray) { return true; } }); }); /** @module ember-data */ define('ember-data/adapters/errors', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateFeatures) { exports.AdapterError = AdapterError; exports.errorsHashToArray = errorsHashToArray; exports.errorsArrayToHash = errorsArrayToHash; var EmberError = _ember.default.Error; var SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/; var SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/; var PRIMARY_ATTRIBUTE_KEY = 'base'; /** @class AdapterError @namespace DS */ function AdapterError(errors) { var message = arguments.length <= 1 || arguments[1] === undefined ? 'Adapter operation failed' : arguments[1]; this.isAdapterError = true; EmberError.call(this, message); this.errors = errors || [{ title: 'Adapter Error', detail: message }]; } var extendedErrorsEnabled = false; if ((0, _emberDataPrivateFeatures.default)('ds-extended-errors')) { extendedErrorsEnabled = true; } function extendFn(ErrorClass) { return function () { var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var defaultMessage = _ref.message; return extend(ErrorClass, defaultMessage); }; } function extend(ParentErrorClass, defaultMessage) { var ErrorClass = function (errors, message) { (0, _emberDataPrivateDebug.assert)('`AdapterError` expects json-api formatted errors array.', Array.isArray(errors || [])); ParentErrorClass.call(this, errors, message || defaultMessage); }; ErrorClass.prototype = Object.create(ParentErrorClass.prototype); if (extendedErrorsEnabled) { ErrorClass.extend = extendFn(ErrorClass); } return ErrorClass; } AdapterError.prototype = Object.create(EmberError.prototype); if (extendedErrorsEnabled) { AdapterError.extend = extendFn(AdapterError); } /** 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. For Ember Data to correctly map errors to their corresponding properties on the model, Ember Data expects each error to be a valid json-api error object with a `source/pointer` that matches the property name. For example if you had a Post model that looked like this. ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr('string'), content: DS.attr('string') }); ``` To show an error from the server related to the `title` and `content` properties your adapter could return a promise that rejects with a `DS.InvalidError` object that looks like this: ```app/adapters/post.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.RESTAdapter.extend({ updateRecord: function() { // Fictional adapter that always rejects return Ember.RSVP.reject(new DS.InvalidError([ { detail: 'Must be unique', source: { pointer: '/data/attributes/title' } }, { detail: 'Must not be blank', source: { pointer: '/data/attributes/content'} } ])); } }); ``` Your backend may use different property names for your records the store will attempt extract and normalize the errors using the serializer's `extractErrors` method before the errors get added to the the model. As a result, it is safe for the `InvalidError` to wrap the error payload unaltered. @class InvalidError @namespace DS */ var InvalidError = extend(AdapterError, 'The adapter rejected the commit because it was invalid'); exports.InvalidError = InvalidError; /** @class TimeoutError @namespace DS */ var TimeoutError = extend(AdapterError, 'The adapter operation timed out'); exports.TimeoutError = TimeoutError; /** @class AbortError @namespace DS */ var AbortError = extend(AdapterError, 'The adapter operation was aborted'); exports.AbortError = AbortError; /** @class UnauthorizedError @namespace DS */ var UnauthorizedError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation is unauthorized') : null; exports.UnauthorizedError = UnauthorizedError; /** @class ForbiddenError @namespace DS */ var ForbiddenError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation is forbidden') : null; exports.ForbiddenError = ForbiddenError; /** @class NotFoundError @namespace DS */ var NotFoundError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter could not find the resource') : null; exports.NotFoundError = NotFoundError; /** @class ConflictError @namespace DS */ var ConflictError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation failed due to a conflict') : null; exports.ConflictError = ConflictError; /** @class ServerError @namespace DS */ var ServerError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation failed due to a server error') : null; exports.ServerError = ServerError; /** @method errorsHashToArray @private */ function errorsHashToArray(errors) { var out = []; if (_ember.default.isPresent(errors)) { Object.keys(errors).forEach(function (key) { var messages = _ember.default.makeArray(errors[key]); for (var i = 0; i < messages.length; i++) { var title = 'Invalid Attribute'; var pointer = '/data/attributes/' + key; if (key === PRIMARY_ATTRIBUTE_KEY) { title = 'Invalid Document'; pointer = '/data'; } out.push({ title: title, detail: messages[i], source: { pointer: pointer } }); } }); } return out; } /** @method errorsArrayToHash @private */ function errorsArrayToHash(errors) { var out = {}; if (_ember.default.isPresent(errors)) { errors.forEach(function (error) { if (error.source && error.source.pointer) { var key = error.source.pointer.match(SOURCE_POINTER_REGEXP); if (key) { key = key[2]; } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) { key = PRIMARY_ATTRIBUTE_KEY; } if (key) { out[key] = out[key] || []; out[key].push(error.detail || error.title); } } }); } return out; } }); define('ember-data/adapters/json-api', ['exports', 'ember', 'ember-data/adapters/rest', 'ember-data/-private/features', 'ember-data/-private/debug'], function (exports, _ember, _emberDataAdaptersRest, _emberDataPrivateFeatures, _emberDataPrivateDebug) { /** @since 1.13.0 @class JSONAPIAdapter @constructor @namespace DS @extends DS.RESTAdapter */ var JSONAPIAdapter = _emberDataAdaptersRest.default.extend({ defaultSerializer: '-json-api', /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ ajaxOptions: function (url, type, options) { var hash = this._super.apply(this, arguments); if (hash.contentType) { hash.contentType = 'application/vnd.api+json'; } var beforeSend = hash.beforeSend; hash.beforeSend = function (xhr) { xhr.setRequestHeader('Accept', 'application/vnd.api+json'); if (beforeSend) { beforeSend(xhr); } }; return hash; }, /** By default the JSONAPIAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { post: { id: 1, comments: [1, 2] } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?filter[id]=1,2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ``` will also send a request to: `GET /comments?filter[id]=1,2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, /** @method findMany @param {DS.Store} store @param {DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function (store, type, ids, snapshots) { if (true && !this._hasCustomizedAjax()) { return this._super.apply(this, arguments); } else { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { filter: { id: ids.join(',') } } }); } }, /** @method pathForType @param {String} modelName @return {String} path **/ pathForType: function (modelName) { var dasherized = _ember.default.String.dasherize(modelName); return _ember.default.String.pluralize(dasherized); }, // TODO: Remove this once we have a better way to override HTTP verbs. /** @method updateRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function (store, type, snapshot) { if (true && !this._hasCustomizedAjax()) { return this._super.apply(this, arguments); } else { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); var id = snapshot.id; var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, 'PATCH', { data: data }); } }, _hasCustomizedAjax: function () { if (this.ajax !== JSONAPIAdapter.prototype.ajax) { (0, _emberDataPrivateDebug.deprecate)('JSONAPIAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.json-api-adapter.ajax', until: '3.0.0' }); return true; } if (this.ajaxOptions !== JSONAPIAdapter.prototype.ajaxOptions) { (0, _emberDataPrivateDebug.deprecate)('JSONAPIAdapterr#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.json-api-adapter.ajax-options', until: '3.0.0' }); return true; } return false; } }); if (true) { JSONAPIAdapter.reopen({ methodForRequest: function (params) { if (params.requestType === 'updateRecord') { return 'PATCH'; } return this._super.apply(this, arguments); }, dataForRequest: function (params) { var requestType = params.requestType; var ids = params.ids; if (requestType === 'findMany') { return { filter: { id: ids.join(',') } }; } if (requestType === 'updateRecord') { var store = params.store; var type = params.type; var snapshot = params.snapshot; var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return data; } return this._super.apply(this, arguments); }, headersForRequest: function () { var headers = this._super.apply(this, arguments) || {}; headers['Accept'] = 'application/vnd.api+json'; return headers; }, _requestToJQueryAjaxHash: function () { var hash = this._super.apply(this, arguments); if (hash.contentType) { hash.contentType = 'application/vnd.api+json'; } return hash; } }); } exports.default = JSONAPIAdapter; }); /** @module ember-data */ define('ember-data/adapters/rest', ['exports', 'ember', 'ember-data/adapter', 'ember-data/adapters/errors', 'ember-data/-private/adapters/build-url-mixin', 'ember-data/-private/features', 'ember-data/-private/debug', 'ember-data/-private/utils/parse-response-headers'], function (exports, _ember, _emberDataAdapter, _emberDataAdaptersErrors, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateFeatures, _emberDataPrivateDebug, _emberDataPrivateUtilsParseResponseHeaders) { var MapWithDefault = _ember.default.MapWithDefault; var get = _ember.default.get; var Promise = _ember.default.RSVP.Promise; /** 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. ## Success and failure The REST adapter will consider a success any response with a status code of the 2xx family ("Success"), as well as 304 ("Not Modified"). Any other status code will be considered a failure. On success, the request promise will be resolved with the full response payload. Failed responses with status code 422 ("Unprocessable Entity") will be considered "invalid". The response will be discarded, except for the `errors` key. The request promise will be rejected with a `DS.InvalidError`. This error object will encapsulate the saved `errors` value. Any other status codes will be treated as an "adapter error". The request promise will be rejected, similarly to the "invalid" case, but with an instance of `DS.AdapterError` instead. ## 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": { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` Similarly, in response to a `GET` request for `/posts`, the JSON should look like this: ```js { "posts": [ { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" }, { "id": 2, "title": "Rails is omakase", "author": "D2H" } ] } ``` Note that the object root can be pluralized for both a single-object response and an array response: the REST adapter is not strict on this. Further, if the HTTP server responds to a `GET` request to `/posts/1` (e.g. the response to a `findRecord` query) with more than one object in the array, Ember Data will only display the object with the matching ID. ### 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: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "id": 5, "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ### Errors If a response is considered a failure, the JSON payload is expected to include a top-level key `errors`, detailing any specific issues. For example: ```js { "errors": { "msg": "Something went wrong" } } ``` This adapter does not make any assumptions as to the format of the `errors` object. It will simply be passed along as is, wrapped in an instance of `DS.InvalidError` or `DS.AdapterError`. The serializer can interpret it afterwards. ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `Person` model would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ 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. ```app/adapters/application.js import DS from 'ember-data'; export default 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. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed('session.authToken', function() { return { "API_KEY": this.get("session.authToken"), "ANOTHER_HEADER": "Some header value" }; }) }); ``` 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-cached mode causing the headers to be recomputed with every request. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed(function() { return { "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), "ANOTHER_HEADER": "Some header value" }; }).volatile() }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter @uses DS.BuildURLMixin */ var RESTAdapter = _emberDataAdapter.default.extend(_emberDataPrivateAdaptersBuildUrlMixin.default, { defaultSerializer: '-rest', /** By default, the RESTAdapter will send the query params sorted alphabetically to the server. For example: ```js store.query('posts', { sort: 'price', category: 'pets' }); ``` will generate a requests like this `/posts?category=pets&sort=price`, even if the parameters were specified in a different order. That way the generated URL will be deterministic and that simplifies caching mechanisms in the backend. Setting `sortQueryParams` to a falsey value will respect the original order. In case you want to sort the query parameters with a different criteria, set `sortQueryParams` to your custom sort function. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ sortQueryParams: function(params) { var sortedKeys = Object.keys(params).sort().reverse(); var len = sortedKeys.length, newParams = {}; for (var i = 0; i < len; i++) { newParams[sortedKeys[i]] = params[sortedKeys[i]]; } return newParams; } }); ``` @method sortQueryParams @param {Object} obj @return {Object} */ sortQueryParams: function (obj) { var keys = Object.keys(obj); var len = keys.length; if (len < 2) { return obj; } var newQueryParams = {}; var sortedKeys = keys.sort(); for (var i = 0; i < len; i++) { newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]]; } return newQueryParams; }, /** By default the RESTAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { post: { id: 1, comments: [1, 2] } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?ids[]=1&ids[]=2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ``` will also send a request to: `GET /comments?ids[]=1&ids[]=2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `Post` model would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.example.com' }); ``` Requests for the `Post` model 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). ```app/adapters/application.js import DS from 'ember-data'; export default 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 `findRecord` 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. @since 1.13.0 @method findRecord @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ findRecord: function (store, type, id, snapshot) { if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, id: id, snapshot: snapshot, requestType: 'findRecord' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); var query = this.buildQuery(snapshot); return this.ajax(url, 'GET', { data: query }); } }, /** 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. @method findAll @param {DS.Store} store @param {DS.Model} type @param {String} sinceToken @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Promise} promise */ findAll: function (store, type, sinceToken, snapshotRecordArray) { var query = this.buildQuery(snapshotRecordArray); if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, sinceToken: sinceToken, query: query, snapshots: snapshotRecordArray, requestType: 'findAll' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, snapshotRecordArray, 'findAll'); if (sinceToken) { query.since = sinceToken; } return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `query` 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. @method query @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ query: function (store, type, query) { if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, query: query, requestType: 'query' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, null, 'query', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch a JSON object for the record that matches a particular query. The `queryRecord` 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. @since 1.13.0 @method queryRecord @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ queryRecord: function (store, type, query) { if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, query: query, requestType: 'queryRecord' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, null, 'queryRecord', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch several records together if `coalesceFindRequests` is true 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 {DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function (store, type, ids, snapshots) { if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, ids: ids, snapshots: snapshots, requestType: 'findMany' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, '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. The format of your `links` value will influence the final request URL via the `urlPrefix` method: * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. @method findHasMany @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findHasMany: function (store, snapshot, url, relationship) { if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, snapshot: snapshot, url: url, relationship: relationship, requestType: 'findHasMany' }); return this._makeRequest(request); } else { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findHasMany')); return this.ajax(url, 'GET'); } }, /** Called by the store in order to fetch the JSON for the unloaded record in a belongs-to relationship that was 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. The format of your `links` value will influence the final request URL via the `urlPrefix` method: * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. @method findBelongsTo @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findBelongsTo: function (store, snapshot, url, relationship) { if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, snapshot: snapshot, url: url, relationship: relationship, requestType: 'findBelongsTo' }); return this._makeRequest(request); } else { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findBelongsTo')); return this.ajax(url, '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 {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: function (store, type, snapshot) { if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'createRecord' }); return this._makeRequest(request); } else { var data = {}; var serializer = store.serializerFor(type.modelName); var url = this.buildURL(type.modelName, null, snapshot, 'createRecord'); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return this.ajax(url, "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 {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function (store, type, snapshot) { if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'updateRecord' }); return this._makeRequest(request); } else { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot); var id = snapshot.id; var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, "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 {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: function (store, type, snapshot) { if (true && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'deleteRecord' }); return this._makeRequest(request); } else { var id = snapshot.id; return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE"); } }, _stripIDFromURL: function (store, snapshot) { var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot); var expandedURL = url.split('/'); // Case when the url is of the format ...something/:id // We are decodeURIComponent-ing the lastSegment because if it represents // the id, it has been encodeURIComponent-ified within `buildURL`. If we // don't do this, then records with id having special characters are not // coalesced correctly (see GH #4190 for the reported bug) var lastSegment = expandedURL[expandedURL.length - 1]; var id = snapshot.id; if (decodeURIComponent(lastSegment) === id) { expandedURL[expandedURL.length - 1] = ""; } else if (endsWith(lastSegment, '?id=' + id)) { //Case when the url is of the format ...something?id=:id expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); } return expandedURL.join('/'); }, // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers maxURLLength: 2048, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. This implementation groups together records that have the same base URL but differing ids. For example `/comments/1` and `/comments/2` will be grouped together because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2` It also supports urls where ids are passed as a query param, such as `/comments?id=1` but not those where there is more than 1 query param such as `/comments?id=2&name=David` Currently only the query param of `id` is supported. If you need to support others, please override this or the `_stripIDFromURL` method. It does not group records that have differing base urls, such as for example: `/posts/1/comments/2` and `/posts/2/comments/3` @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, snapshots) { var groups = MapWithDefault.create({ defaultValue: function () { return []; } }); var adapter = this; var maxURLLength = this.maxURLLength; snapshots.forEach(function (snapshot) { var baseUrl = adapter._stripIDFromURL(store, snapshot); groups.get(baseUrl).push(snapshot); }); function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) { var baseUrl = adapter._stripIDFromURL(store, group[0]); var idsSize = 0; var splitGroups = [[]]; group.forEach(function (snapshot) { var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength; if (baseUrl.length + idsSize + additionalLength >= maxURLLength) { idsSize = 0; splitGroups.push([]); } idsSize += additionalLength; var lastGroupIndex = splitGroups.length - 1; splitGroups[lastGroupIndex].push(snapshot); }); return splitGroups; } var groupsArray = []; groups.forEach(function (group, key) { var paramNameLength = '&ids%5B%5D='.length; var splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength); splitGroups.forEach(function (splitGroup) { return groupsArray.push(splitGroup); }); }); return groupsArray; }, /** Takes an ajax response, and returns the json payload or an error. By default this hook just returns the json payload passed to it. You might want to override it in two cases: 1. Your API might return useful results in the response headers. Response headers are passed in as the second argument. 2. Your API might return errors as successful responses with status code 200 and an Errors text or object. You can return a `DS.InvalidError` or a `DS.AdapterError` (or a sub class) from this hook and it will automatically reject the promise and put your record into the invalid or error state. 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. When returning an `DS.InvalidError` the store will attempt to normalize the error data returned from the server using the serializer's `extractErrors` method. @since 1.13.0 @method handleResponse @param {Number} status @param {Object} headers @param {Object} payload @param {Object} requestData - the original request information @return {Object | DS.AdapterError} response */ handleResponse: function (status, headers, payload, requestData) { if (this.isSuccess(status, headers, payload)) { return payload; } else if (this.isInvalid(status, headers, payload)) { return new _emberDataAdaptersErrors.InvalidError(payload.errors); } var errors = this.normalizeErrorResponse(status, headers, payload); var detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData); if ((0, _emberDataPrivateFeatures.default)('ds-extended-errors')) { switch (status) { case 401: return new _emberDataAdaptersErrors.UnauthorizedError(errors, detailedMessage); case 403: return new _emberDataAdaptersErrors.ForbiddenError(errors, detailedMessage); case 404: return new _emberDataAdaptersErrors.NotFoundError(errors, detailedMessage); case 409: return new _emberDataAdaptersErrors.ConflictError(errors, detailedMessage); default: if (status >= 500) { return new _emberDataAdaptersErrors.ServerError(errors, detailedMessage); } } } return new _emberDataAdaptersErrors.AdapterError(errors, detailedMessage); }, /** Default `handleResponse` implementation uses this hook to decide if the response is a success. @since 1.13.0 @method isSuccess @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isSuccess: function (status, headers, payload) { return status >= 200 && status < 300 || status === 304; }, /** Default `handleResponse` implementation uses this hook to decide if the response is a an invalid error. @since 1.13.0 @method isInvalid @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isInvalid: function (status, headers, payload) { return status === 422; }, /** 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} options @return {Promise} promise */ ajax: function (url, type, options) { var adapter = this; var requestData = { url: url, method: type }; return new Promise(function (resolve, reject) { var hash = adapter.ajaxOptions(url, type, options); hash.success = function (payload, textStatus, jqXHR) { var response = ajaxSuccess(adapter, jqXHR, payload, requestData); _ember.default.run.join(null, resolve, response); }; hash.error = function (jqXHR, textStatus, errorThrown) { var responseData = { textStatus: textStatus, errorThrown: errorThrown }; var error = ajaxError(adapter, jqXHR, requestData, responseData); _ember.default.run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, 'DS: RESTAdapter#ajax ' + type + ' to ' + url); }, /** @method _ajaxRequest @private @param {Object} options jQuery ajax options to be used for the ajax request */ _ajaxRequest: function (options) { _ember.default.$.ajax(options); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ ajaxOptions: function (url, type, options) { var hash = options || {}; 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) { Object.keys(headers).forEach(function (key) { return xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, /** @method parseErrorResponse @private @param {String} responseText @return {Object} */ parseErrorResponse: function (responseText) { var json = responseText; try { json = _ember.default.$.parseJSON(responseText); } catch (e) { // ignored } return json; }, /** @method normalizeErrorResponse @private @param {Number} status @param {Object} headers @param {Object} payload @return {Array} errors payload */ normalizeErrorResponse: function (status, headers, payload) { if (payload && typeof payload === 'object' && payload.errors) { return payload.errors; } else { return [{ status: '' + status, title: "The backend responded with an error", detail: '' + payload }]; } }, /** Generates a detailed ("friendly") error message, with plenty of information for debugging (good luck!) @method generatedDetailedMessage @private @param {Number} status @param {Object} headers @param {Object} payload @param {Object} requestData @return {String} detailed error message */ generatedDetailedMessage: function (status, headers, payload, requestData) { var shortenedPayload; var payloadContentType = headers["Content-Type"] || "Empty Content-Type"; if (payloadContentType === "text/html" && payload.length > 250) { shortenedPayload = "[Omitted Lengthy HTML]"; } else { shortenedPayload = payload; } var requestDescription = requestData.method + ' ' + requestData.url; var payloadDescription = 'Payload (' + payloadContentType + ')'; return ['Ember Data Request ' + requestDescription + ' returned a ' + status, payloadDescription, shortenedPayload].join('\n'); }, // @since 2.5.0 buildQuery: function (snapshot) { var query = {}; if (snapshot) { var include = snapshot.include; if (include) { query.include = include; } } return query; }, _hasCustomizedAjax: function () { if (this.ajax !== RESTAdapter.prototype.ajax) { (0, _emberDataPrivateDebug.deprecate)('RESTAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.rest-adapter.ajax', until: '3.0.0' }); return true; } if (this.ajaxOptions !== RESTAdapter.prototype.ajaxOptions) { (0, _emberDataPrivateDebug.deprecate)('RESTAdapter#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.rest-adapter.ajax-options', until: '3.0.0' }); return true; } return false; } }); if (true) { RESTAdapter.reopen({ /** * Get the data (body or query params) for a request. * * @public * @method dataForRequest * @param {Object} params * @return {Object} data */ dataForRequest: function (params) { var store = params.store; var type = params.type; var snapshot = params.snapshot; var requestType = params.requestType; var query = params.query; // type is not passed to findBelongsTo and findHasMany type = type || snapshot && snapshot.type; var serializer = store.serializerFor(type.modelName); var data = {}; switch (requestType) { case 'createRecord': serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); break; case 'updateRecord': serializer.serializeIntoHash(data, type, snapshot); break; case 'findRecord': data = this.buildQuery(snapshot); break; case 'findAll': if (params.sinceToken) { query = query || {}; query.since = params.sinceToken; } data = query; break; case 'query': case 'queryRecord': if (this.sortQueryParams) { query = this.sortQueryParams(query); } data = query; break; case 'findMany': data = { ids: params.ids }; break; default: data = undefined; break; } return data; }, /** * Get the HTTP method for a request. * * @public * @method methodForRequest * @param {Object} params * @return {String} HTTP method */ methodForRequest: function (params) { var requestType = params.requestType; switch (requestType) { case 'createRecord': return 'POST'; case 'updateRecord': return 'PUT'; case 'deleteRecord': return 'DELETE'; } return 'GET'; }, /** * Get the URL for a request. * * @public * @method urlForRequest * @param {Object} params * @return {String} URL */ urlForRequest: function (params) { var type = params.type; var id = params.id; var ids = params.ids; var snapshot = params.snapshot; var snapshots = params.snapshots; var requestType = params.requestType; var query = params.query; // type and id are not passed from updateRecord and deleteRecord, hence they // are defined if not set type = type || snapshot && snapshot.type; id = id || snapshot && snapshot.id; switch (requestType) { case 'findAll': return this.buildURL(type.modelName, null, snapshots, requestType); case 'query': case 'queryRecord': return this.buildURL(type.modelName, null, null, requestType, query); case 'findMany': return this.buildURL(type.modelName, ids, snapshots, requestType); case 'findHasMany': case 'findBelongsTo': { var url = this.buildURL(type.modelName, id, snapshot, requestType); return this.urlPrefix(params.url, url); } } return this.buildURL(type.modelName, id, snapshot, requestType, query); }, /** * Get the headers for a request. * * By default the value of the `headers` property of the adapter is * returned. * * @public * @method headersForRequest * @param {Object} params * @return {Object} headers */ headersForRequest: function (params) { return this.get('headers'); }, /** * Get an object which contains all properties for a request which should * be made. * * @private * @method _requestFor * @param {Object} params * @return {Object} request object */ _requestFor: function (params) { var method = this.methodForRequest(params); var url = this.urlForRequest(params); var headers = this.headersForRequest(params); var data = this.dataForRequest(params); return { method: method, url: url, headers: headers, data: data }; }, /** * Convert a request object into a hash which can be passed to `jQuery.ajax`. * * @private * @method _requestToJQueryAjaxHash * @param {Object} request * @return {Object} jQuery ajax hash */ _requestToJQueryAjaxHash: function (request) { var hash = {}; hash.type = request.method; hash.url = request.url; hash.dataType = 'json'; hash.context = this; if (request.data) { if (request.method !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(request.data); } else { hash.data = request.data; } } var headers = request.headers; if (headers !== undefined) { hash.beforeSend = function (xhr) { Object.keys(headers).forEach(function (key) { return xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, /** * Make a request using `jQuery.ajax`. * * @private * @method _makeRequest * @param {Object} request * @return {Promise} promise */ _makeRequest: function (request) { var adapter = this; var hash = this._requestToJQueryAjaxHash(request); var method = request.method; var url = request.url; var requestData = { method: method, url: url }; return new _ember.default.RSVP.Promise(function (resolve, reject) { hash.success = function (payload, textStatus, jqXHR) { var response = ajaxSuccess(adapter, jqXHR, payload, requestData); _ember.default.run.join(null, resolve, response); }; hash.error = function (jqXHR, textStatus, errorThrown) { var responseData = { textStatus: textStatus, errorThrown: errorThrown }; var error = ajaxError(adapter, jqXHR, requestData, responseData); _ember.default.run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, 'DS: RESTAdapter#makeRequest: ' + method + ' ' + url); } }); } function ajaxSuccess(adapter, jqXHR, payload, requestData) { var response = undefined; try { response = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders.default)(jqXHR.getAllResponseHeaders()), payload, requestData); } catch (error) { return Promise.reject(error); } if (response && response.isAdapterError) { return Promise.reject(response); } else { return response; } } function ajaxError(adapter, jqXHR, requestData, responseData) { (0, _emberDataPrivateDebug.runInDebug)(function () { var message = 'The server returned an empty string for ' + requestData.method + ' ' + requestData.url + ', which cannot be parsed into a valid JSON. Return either null or {}.'; var validJSONString = !(responseData.textStatus === "parsererror" && jqXHR.responseText === ""); (0, _emberDataPrivateDebug.warn)(message, validJSONString, { id: 'ds.adapter.returned-empty-string-as-JSON' }); }); var error = undefined; if (responseData.errorThrown instanceof Error) { error = responseData.errorThrown; } else if (responseData.textStatus === 'timeout') { error = new _emberDataAdaptersErrors.TimeoutError(); } else if (responseData.textStatus === 'abort' || jqXHR.status === 0) { error = new _emberDataAdaptersErrors.AbortError(); } else { try { error = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders.default)(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || responseData.errorThrown, requestData); } catch (e) { error = e; } } return error; } //From http://stackoverflow.com/questions/280634/endswith-in-javascript function endsWith(string, suffix) { if (typeof String.prototype.endsWith !== 'function') { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } } exports.default = RESTAdapter; }); /** @module ember-data */ define('ember-data/attr', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { exports.default = attr; /** @module ember-data */ function getDefaultValue(record, options, key) { if (typeof options.defaultValue === 'function') { return options.defaultValue.apply(null, arguments); } else { var defaultValue = options.defaultValue; (0, _emberDataPrivateDebug.deprecate)('Non primitive defaultValues are deprecated because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.', typeof defaultValue !== 'object' || defaultValue === null, { id: 'ds.defaultValue.complex-object', until: '3.0.0' }); return defaultValue; } } function hasValue(record, key) { return key in record._attributes || key in record._inFlightAttributes || key in record._data; } function getValue(record, key) { if (key in record._attributes) { return record._attributes[key]; } else if (key in record._inFlightAttributes) { 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 ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: DS.attr('string'), email: DS.attr('string'), verified: DS.attr('boolean', { defaultValue: false }) }); ``` Default value can also be a function. This is useful it you want to return a new object for each attribute. ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: attr('string'), email: attr('string'), settings: attr({defaultValue: function() { return {}; }}) }); ``` The `options` hash is passed as second argument to a transforms' `serialize` and `deserialize` method. This allows to configure a transformation and adapt the corresponding value, based on the config: ```app/models/post.js export default DS.Model.extend({ text: DS.attr('text', { uppercase: true }) }); ``` ```app/transforms/text.js export default DS.Transform.extend({ serialize: function(value, options) { if (options.uppercase) { return value.toUpperCase(); } return value; }, deserialize: function(value) { return value; } }) ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ function attr(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { options = options || {}; } var meta = { type: type, isAttribute: true, options: options }; return _ember.default.computed({ get: function (key) { var internalModel = this._internalModel; if (hasValue(internalModel, key)) { return getValue(internalModel, key); } else { return getDefaultValue(this, options, key); } }, set: function (key, value) { var internalModel = this._internalModel; var oldValue = getValue(internalModel, key); var originalValue; 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 internalModel._attributes[key] = value; if (key in internalModel._inFlightAttributes) { originalValue = internalModel._inFlightAttributes[key]; } else { originalValue = internalModel._data[key]; } this._internalModel.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: originalValue, value: value }); } return value; } }).meta(meta); } }); define("ember-data", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/features", "ember-data/-private/global", "ember-data/-private/core", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/model/internal-model", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/store", "ember-data/-private/system/model", "ember-data/model", "ember-data/-private/system/snapshot", "ember-data/adapter", "ember-data/serializer", "ember-data/-private/system/debug", "ember-data/adapters/errors", "ember-data/-private/system/record-arrays", "ember-data/-private/system/many-array", "ember-data/-private/system/record-array-manager", "ember-data/-private/adapters", "ember-data/-private/adapters/build-url-mixin", "ember-data/-private/serializers", "ember-inflector", "ember-data/serializers/embedded-records-mixin", "ember-data/-private/transforms", "ember-data/relationships", "ember-data/setup-container", "ember-data/-private/instance-initializers/initialize-store-service", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateFeatures, _emberDataPrivateGlobal, _emberDataPrivateCore, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStore, _emberDataPrivateSystemModel, _emberDataModel, _emberDataPrivateSystemSnapshot, _emberDataAdapter, _emberDataSerializer, _emberDataPrivateSystemDebug, _emberDataAdaptersErrors, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemManyArray, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateAdapters, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateSerializers, _emberInflector, _emberDataSerializersEmbeddedRecordsMixin, _emberDataPrivateTransforms, _emberDataRelationships, _emberDataSetupContainer, _emberDataPrivateInstanceInitializersInitializeStoreService, _emberDataPrivateSystemRelationshipsStateRelationship) { /** Ember Data @module ember-data @main ember-data */ if (_ember.default.VERSION.match(/^1\.([0-9]|1[0-2])\./)) { throw new _ember.default.Error("Ember Data requires at least Ember 1.13.0, but you have " + _ember.default.VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data."); } _emberDataPrivateCore.default.Store = _emberDataPrivateSystemStore.Store; _emberDataPrivateCore.default.PromiseArray = _emberDataPrivateSystemPromiseProxies.PromiseArray; _emberDataPrivateCore.default.PromiseObject = _emberDataPrivateSystemPromiseProxies.PromiseObject; _emberDataPrivateCore.default.PromiseManyArray = _emberDataPrivateSystemPromiseProxies.PromiseManyArray; _emberDataPrivateCore.default.Model = _emberDataModel.default; _emberDataPrivateCore.default.RootState = _emberDataPrivateSystemModel.RootState; _emberDataPrivateCore.default.attr = _emberDataPrivateSystemModel.attr; _emberDataPrivateCore.default.Errors = _emberDataPrivateSystemModel.Errors; _emberDataPrivateCore.default.InternalModel = _emberDataPrivateSystemModelInternalModel.default; _emberDataPrivateCore.default.Snapshot = _emberDataPrivateSystemSnapshot.default; _emberDataPrivateCore.default.Adapter = _emberDataAdapter.default; _emberDataPrivateCore.default.AdapterError = _emberDataAdaptersErrors.AdapterError; _emberDataPrivateCore.default.InvalidError = _emberDataAdaptersErrors.InvalidError; _emberDataPrivateCore.default.TimeoutError = _emberDataAdaptersErrors.TimeoutError; _emberDataPrivateCore.default.AbortError = _emberDataAdaptersErrors.AbortError; if ((0, _emberDataPrivateFeatures.default)('ds-extended-errors')) { _emberDataPrivateCore.default.UnauthorizedError = _emberDataAdaptersErrors.UnauthorizedError; _emberDataPrivateCore.default.ForbiddenError = _emberDataAdaptersErrors.ForbiddenError; _emberDataPrivateCore.default.NotFoundError = _emberDataAdaptersErrors.NotFoundError; _emberDataPrivateCore.default.ConflictError = _emberDataAdaptersErrors.ConflictError; _emberDataPrivateCore.default.ServerError = _emberDataAdaptersErrors.ServerError; } _emberDataPrivateCore.default.errorsHashToArray = _emberDataAdaptersErrors.errorsHashToArray; _emberDataPrivateCore.default.errorsArrayToHash = _emberDataAdaptersErrors.errorsArrayToHash; _emberDataPrivateCore.default.Serializer = _emberDataSerializer.default; _emberDataPrivateCore.default.DebugAdapter = _emberDataPrivateSystemDebug.default; _emberDataPrivateCore.default.RecordArray = _emberDataPrivateSystemRecordArrays.RecordArray; _emberDataPrivateCore.default.FilteredRecordArray = _emberDataPrivateSystemRecordArrays.FilteredRecordArray; _emberDataPrivateCore.default.AdapterPopulatedRecordArray = _emberDataPrivateSystemRecordArrays.AdapterPopulatedRecordArray; _emberDataPrivateCore.default.ManyArray = _emberDataPrivateSystemManyArray.default; _emberDataPrivateCore.default.RecordArrayManager = _emberDataPrivateSystemRecordArrayManager.default; _emberDataPrivateCore.default.RESTAdapter = _emberDataPrivateAdapters.RESTAdapter; _emberDataPrivateCore.default.BuildURLMixin = _emberDataPrivateAdaptersBuildUrlMixin.default; _emberDataPrivateCore.default.RESTSerializer = _emberDataPrivateSerializers.RESTSerializer; _emberDataPrivateCore.default.JSONSerializer = _emberDataPrivateSerializers.JSONSerializer; _emberDataPrivateCore.default.JSONAPIAdapter = _emberDataPrivateAdapters.JSONAPIAdapter; _emberDataPrivateCore.default.JSONAPISerializer = _emberDataPrivateSerializers.JSONAPISerializer; _emberDataPrivateCore.default.Transform = _emberDataPrivateTransforms.Transform; _emberDataPrivateCore.default.DateTransform = _emberDataPrivateTransforms.DateTransform; _emberDataPrivateCore.default.StringTransform = _emberDataPrivateTransforms.StringTransform; _emberDataPrivateCore.default.NumberTransform = _emberDataPrivateTransforms.NumberTransform; _emberDataPrivateCore.default.BooleanTransform = _emberDataPrivateTransforms.BooleanTransform; _emberDataPrivateCore.default.EmbeddedRecordsMixin = _emberDataSerializersEmbeddedRecordsMixin.default; _emberDataPrivateCore.default.belongsTo = _emberDataRelationships.belongsTo; _emberDataPrivateCore.default.hasMany = _emberDataRelationships.hasMany; _emberDataPrivateCore.default.Relationship = _emberDataPrivateSystemRelationshipsStateRelationship.default; _emberDataPrivateCore.default._setupContainer = _emberDataSetupContainer.default; _emberDataPrivateCore.default._initializeStoreService = _emberDataPrivateInstanceInitializersInitializeStoreService.default; Object.defineProperty(_emberDataPrivateCore.default, 'normalizeModelName', { enumerable: true, writable: false, configurable: false, value: _emberDataPrivateSystemNormalizeModelName.default }); Object.defineProperty(_emberDataPrivateGlobal.default, 'DS', { configurable: true, get: function () { (0, _emberDataPrivateDebug.deprecate)('Using the global version of DS is deprecated. Please either import ' + 'the specific modules needed or `import DS from \'ember-data\';`.', false, { id: 'ember-data.global-ds', until: '3.0.0' }); return _emberDataPrivateCore.default; } }); exports.default = _emberDataPrivateCore.default; }); define('ember-data/initializers/data-adapter', ['exports', 'ember'], function (exports, _ember) { /* This initializer is here to keep backwards compatibility with code depending on the `data-adapter` initializer (before Ember Data was an addon). Should be removed for Ember Data 3.x */ exports.default = { name: 'data-adapter', before: 'store', initialize: _ember.default.K }; }); define('ember-data/initializers/ember-data', ['exports', 'ember-data/setup-container', 'ember-data/-private/core'], function (exports, _emberDataSetupContainer, _emberDataPrivateCore) { /* 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.StoreService` (or via a module system that resolves to `service:store`) 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.StoreService = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.Controller.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. */ exports.default = { name: 'ember-data', initialize: _emberDataSetupContainer.default }; }); define('ember-data/initializers/injectStore', ['exports', 'ember'], function (exports, _ember) { /* This initializer is here to keep backwards compatibility with code depending on the `injectStore` initializer (before Ember Data was an addon). Should be removed for Ember Data 3.x */ exports.default = { name: 'injectStore', before: 'store', initialize: _ember.default.K }; }); define('ember-data/initializers/store', ['exports', 'ember'], function (exports, _ember) { /* This initializer is here to keep backwards compatibility with code depending on the `store` initializer (before Ember Data was an addon). Should be removed for Ember Data 3.x */ exports.default = { name: 'store', after: 'ember-data', initialize: _ember.default.K }; }); define('ember-data/initializers/transforms', ['exports', 'ember'], function (exports, _ember) { /* This initializer is here to keep backwards compatibility with code depending on the `transforms` initializer (before Ember Data was an addon). Should be removed for Ember Data 3.x */ exports.default = { name: 'transforms', before: 'store', initialize: _ember.default.K }; }); define("ember-data/instance-initializers/ember-data", ["exports", "ember-data/-private/instance-initializers/initialize-store-service"], function (exports, _emberDataPrivateInstanceInitializersInitializeStoreService) { exports.default = { name: "ember-data", initialize: _emberDataPrivateInstanceInitializersInitializeStoreService.default }; }); define("ember-data/model", ["exports", "ember-data/-private/system/model"], function (exports, _emberDataPrivateSystemModel) { exports.default = _emberDataPrivateSystemModel.default; }); define("ember-data/relationships", ["exports", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many"], function (exports, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany) { exports.belongsTo = _emberDataPrivateSystemRelationshipsBelongsTo.default; exports.hasMany = _emberDataPrivateSystemRelationshipsHasMany.default; }); /** @module ember-data */ define('ember-data/serializer', ['exports', 'ember'], function (exports, _ember) { /** `DS.Serializer` 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: * `normalizeResponse()` * `serialize()` And you can optionally override the following methods: * `normalize()` For an example implementation, see [DS.JSONSerializer](DS.JSONSerializer.html), the included JSON serializer. @class Serializer @namespace DS @extends Ember.Object */ exports.default = _ember.default.Object.extend({ /** The `store` property is the application's `store` that contains all records. It's injected as a service. It can be used to push records from a non flat data structure server response. @property store @type {DS.Store} @public */ /** The `normalizeResponse` method is used to normalize a payload from the server to a JSON-API Document. http://jsonapi.org/format/#document-structure @since 1.13.0 @method normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeResponse: null, /** The `serialize` method is used when a record is saved in order to convert the record into the form that your external data source expects. `serialize` takes an optional `options` hash with a single option: - `includeId`: If this is `true`, `serialize` should include the ID in the serialized object it builds. @method serialize @param {DS.Model} record @param {Object} [options] @return {Object} */ serialize: null, /** The `normalize` method is used to convert a payload received from your external data source into the normalized form `store.push()` expects. You should override this method, munge the hash and return the normalized payload. @method normalize @param {DS.Model} typeClass @param {Object} hash @return {Object} */ normalize: function (typeClass, hash) { return hash; } }); }); /** @module ember-data */ define('ember-data/serializers/embedded-records-mixin', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { 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); } } var get = _ember.default.get; var set = _ember.default.set; var camelize = _ember.default.String.camelize; /** ## 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). ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: { embedded: 'always' }, comments: { serialize: 'ids' } } }); ``` Note that this use of `{ embedded: 'always' }` is unrelated to the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of defining a model while working with the `ActiveModelSerializer`. Nevertheless, using `{ embedded: 'always' }` as an option to `DS.attr` is not a valid way to setup embedded records. 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 false 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 payload (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 `EmbeddedRecordsMixin`. 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: false`. ### EmbeddedRecordsMixin defaults If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin` will behave in the following way: BelongsTo: `{ serialize: 'id', deserialize: 'id' }` HasMany: `{ serialize: false, deserialize: 'ids' }` ### Model Relationships Embedded records must have a model defined to be extracted and serialized. Note that when defining any relationships on your model such as `belongsTo` and `hasMany`, you should not both specify `async: true` and also indicate through the serializer's `attrs` attribute that the related model should be embedded for deserialization. If a model is declared embedded for deserialization (`embedded: 'always'` or `deserialize: 'records'`), then do not use `async: true`. 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 important to grok what the customizations are. Please read the docs for the methods this mixin provides, in case you need to modify it to fit your specific needs.** For example review the docs for each method of this mixin: * [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize) * [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo) * [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany) @class EmbeddedRecordsMixin @namespace DS */ exports.default = _ember.default.Mixin.create({ /** Normalize the record and recursively normalize/extract all the embedded records while pushing them into the store as they are encountered 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" }] } } ``` @method normalize @param {DS.Model} typeClass @param {Object} hash to be normalized @param {String} prop the hash has been referenced by @return {Object} the normalized hash **/ normalize: function (typeClass, hash, prop) { var normalizedHash = this._super(typeClass, hash, prop); return this._extractEmbeddedRecords(this, this.store, typeClass, normalizedHash); }, keyForRelationship: function (key, typeClass, method) { if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) { return this.keyForAttribute(key, method); } else { return this._super(key, typeClass, method) || key; } }, /** 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 ```app/serializers/post.js import DS from 'ember-data'; export default 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.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function (snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var embeddedSnapshot = snapshot.belongsTo(attr); if (includeIds) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } if (!embeddedSnapshot) { json[serializedKey] = null; } else { json[serializedKey] = embeddedSnapshot.id; if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } } else if (includeRecords) { this._serializeEmbeddedBelongsTo(snapshot, json, relationship); } }, _serializeEmbeddedBelongsTo: function (snapshot, json, relationship) { var embeddedSnapshot = snapshot.belongsTo(relationship.key); var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } if (!embeddedSnapshot) { json[serializedKey] = null; } else { json[serializedKey] = embeddedSnapshot.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[serializedKey]); if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, /** Serializes `hasMany` relationships 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 ```app/serializers/post.js import DS from 'ember-data; export default 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`, `ids-and-types` 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): ```app/serializers/post.js import DS from 'ember-data; export default 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"] } } ``` To embed the relationship as a collection of objects with `id` and `type` keys, set `ids-and-types` for the related object. This is particularly useful for polymorphic relationships where records don't share the same table and the `id` is not enough information. By example having a user that has many pets: ```js User = DS.Model.extend({ name: DS.attr('string'), pets: DS.hasMany('pet', { polymorphic: true }) }); Pet = DS.Model.extend({ name: DS.attr('string'), }); Cat = Pet.extend({ // ... }); Parrot = Pet.extend({ // ... }); ``` ```app/serializers/user.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { pets: { serialize: 'ids-and-types', deserialize: 'records' } } }); ``` ```js { "user": { "id": "1" "name": "Bertin Osborne", "pets": [ { "id": "1", "type": "Cat" }, { "id": "1", "type": "Parrot"} ] } } ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function (snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } if (this.hasSerializeIdsOption(attr)) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } json[serializedKey] = snapshot.hasMany(attr, { ids: true }); } else if (this.hasSerializeRecordsOption(attr)) { this._serializeEmbeddedHasMany(snapshot, json, relationship); } else { if (this.hasSerializeIdsAndTypesOption(attr)) { this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship); } } }, /** Serializes a hasMany relationship as an array of objects containing only `id` and `type` keys. This has its use case on polymorphic hasMany relationships where the server is not storing all records in the same table using STI, and therefore the `id` is not enough information TODO: Make the default in Ember-data 3.0?? */ _serializeHasManyAsIdsAndTypes: function (snapshot, json, relationship) { var serializedKey = this.keyForAttribute(relationship.key, 'serialize'); var hasMany = snapshot.hasMany(relationship.key); json[serializedKey] = _ember.default.A(hasMany).map(function (recordSnapshot) { // // I'm sure I'm being utterly naive here. Propably id is a configurate property and // type too, and the modelName has to be normalized somehow. // return { id: recordSnapshot.id, type: recordSnapshot.modelName }; }); }, _serializeEmbeddedHasMany: function (snapshot, json, relationship) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } (0, _emberDataPrivateDebug.warn)('The embedded relationship \'' + serializedKey + '\' is undefined for \'' + snapshot.modelName + '\' with id \'' + snapshot.id + '\'. Please include it in your original payload.', _ember.default.typeOf(snapshot.hasMany(relationship.key)) !== 'undefined', { id: 'ds.serializer.embedded-relationship-undefined' }); json[serializedKey] = this._generateSerializedHasMany(snapshot, relationship); }, /* Returns an array of embedded records serialized to JSON */ _generateSerializedHasMany: function (snapshot, relationship) { var hasMany = snapshot.hasMany(relationship.key); var manyArray = _ember.default.A(hasMany); var ret = new Array(manyArray.length); for (var i = 0; i < manyArray.length; i++) { var embeddedSnapshot = manyArray[i]; var embeddedJson = embeddedSnapshot.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson); ret[i] = embeddedJson; } return ret; }, /** 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.Snapshot} snapshot @param {DS.Snapshot} embeddedSnapshot @param {Object} relationship @param {Object} json */ removeEmbeddedForeignKey: function (snapshot, embeddedSnapshot, relationship, json) { if (relationship.kind === 'hasMany') { return; } else if (relationship.kind === 'belongsTo') { var parentRecord = snapshot.type.inverseFor(relationship.key, this.store); if (parentRecord) { var name = parentRecord.name; var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName); var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize'); if (parentKey) { delete json[parentKey]; } } } }, // checks config for attrs option to embedded (always) - serialize and deserialize hasEmbeddedAlwaysOption: function (attr) { var option = this.attrsOption(attr); return option && option.embedded === 'always'; }, // checks config for attrs option to serialize ids hasSerializeRecordsOption: function (attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || option && option.serialize === 'records'; }, // checks config for attrs option to serialize records hasSerializeIdsOption: function (attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids' || option.serialize === 'id'); }, // checks config for attrs option to serialize records as objects containing id and types hasSerializeIdsAndTypesOption: function (attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids-and-types' || option.serialize === 'id-and-type'); }, // checks config for attrs option to serialize records noSerializeOptionSpecified: function (attr) { var option = this.attrsOption(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'` hasDeserializeRecordsOption: function (attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || option && option.deserialize === 'records'; }, attrsOption: function (attr) { var attrs = this.get('attrs'); return attrs && (attrs[camelize(attr)] || attrs[attr]); }, /** @method _extractEmbeddedRecords @private */ _extractEmbeddedRecords: function (serializer, store, typeClass, partial) { var _this = this; typeClass.eachRelationship(function (key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { if (relationship.kind === "hasMany") { _this._extractEmbeddedHasMany(store, key, partial, relationship); } if (relationship.kind === "belongsTo") { _this._extractEmbeddedBelongsTo(store, key, partial, relationship); } } }); return partial; }, /** @method _extractEmbeddedHasMany @private */ _extractEmbeddedHasMany: function (store, key, hash, relationshipMeta) { var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var hasMany = new Array(relationshipHash.length); for (var i = 0; i < relationshipHash.length; i++) { var item = relationshipHash[i]; var _normalizeEmbeddedRelationship = this._normalizeEmbeddedRelationship(store, relationshipMeta, item); var data = _normalizeEmbeddedRelationship.data; var included = _normalizeEmbeddedRelationship.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included; (_hash$included = hash.included).push.apply(_hash$included, _toConsumableArray(included)); } hasMany[i] = { id: data.id, type: data.type }; } var relationship = { data: hasMany }; set(hash, 'data.relationships.' + key, relationship); }, /** @method _extractEmbeddedBelongsTo @private */ _extractEmbeddedBelongsTo: function (store, key, hash, relationshipMeta) { var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var _normalizeEmbeddedRelationship2 = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash); var data = _normalizeEmbeddedRelationship2.data; var included = _normalizeEmbeddedRelationship2.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included2; (_hash$included2 = hash.included).push.apply(_hash$included2, _toConsumableArray(included)); } var belongsTo = { id: data.id, type: data.type }; var relationship = { data: belongsTo }; set(hash, 'data.relationships.' + key, relationship); }, /** @method _normalizeEmbeddedRelationship @private */ _normalizeEmbeddedRelationship: function (store, relationshipMeta, relationshipHash) { var modelName = relationshipMeta.type; if (relationshipMeta.options.polymorphic) { modelName = relationshipHash.type; } var modelClass = store.modelFor(modelName); var serializer = store.serializerFor(modelName); return serializer.normalize(modelClass, relationshipHash, null); }, isEmbeddedRecordsMixin: true }); }); define('ember-data/serializers/json-api', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializers/json', 'ember-data/-private/system/normalize-model-name', 'ember-inflector', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializersJson, _emberDataPrivateSystemNormalizeModelName, _emberInflector, _emberDataPrivateFeatures) { var dasherize = _ember.default.String.dasherize; /** Ember Data 2.0 Serializer: 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. `JSONAPISerializer` supports the http://jsonapi.org/ spec and is the serializer recommended by Ember Data. This serializer normalizes a JSON API payload that looks like: ```js // models/player.js import DS from "ember-data"; export default DS.Model.extend({ name: DS.attr(), skill: DS.attr(), gamesPlayed: DS.attr(), club: DS.belongsTo('club') }); // models/club.js import DS from "ember-data"; export default DS.Model.extend({ name: DS.attr(), location: DS.attr(), players: DS.hasMany('player') }); ``` ```js { "data": [ { "attributes": { "name": "Benfica", "location": "Portugal" }, "id": "1", "relationships": { "players": { "data": [ { "id": "3", "type": "players" } ] } }, "type": "clubs" } ], "included": [ { "attributes": { "name": "Eusebio Silva Ferreira", "skill": "Rocket shot", "games-played": 431 }, "id": "3", "relationships": { "club": { "data": { "id": "1", "type": "clubs" } } }, "type": "players" } ] } ``` to the format that the Ember Data store expects. @since 1.13.0 @class JSONAPISerializer @namespace DS @extends DS.JSONSerializer */ var JSONAPISerializer = _emberDataSerializersJson.default.extend({ /** @method _normalizeDocumentHelper @param {Object} documentHash @return {Object} @private */ _normalizeDocumentHelper: function (documentHash) { if (_ember.default.typeOf(documentHash.data) === 'object') { documentHash.data = this._normalizeResourceHelper(documentHash.data); } else if (Array.isArray(documentHash.data)) { var ret = new Array(documentHash.data.length); for (var i = 0; i < documentHash.data.length; i++) { var data = documentHash.data[i]; ret[i] = this._normalizeResourceHelper(data); } documentHash.data = ret; } if (Array.isArray(documentHash.included)) { var ret = new Array(documentHash.included.length); for (var i = 0; i < documentHash.included.length; i++) { var included = documentHash.included[i]; ret[i] = this._normalizeResourceHelper(included); } documentHash.included = ret; } return documentHash; }, /** @method _normalizeRelationshipDataHelper @param {Object} relationshipDataHash @return {Object} @private */ _normalizeRelationshipDataHelper: function (relationshipDataHash) { if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { var modelName = this.modelNameFromPayloadType(relationshipDataHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipDataHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a relationship. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.json-api-serializer.deprecated-model-name-for-relationship', until: '3.0.0' }); modelName = deprecatedModelNameLookup; } relationshipDataHash.type = modelName; } else { var type = this.modelNameFromPayloadKey(relationshipDataHash.type); relationshipDataHash.type = type; } return relationshipDataHash; }, /** @method _normalizeResourceHelper @param {Object} resourceHash @return {Object} @private */ _normalizeResourceHelper: function (resourceHash) { (0, _emberDataPrivateDebug.assert)(this.warnMessageForUndefinedType(), !_ember.default.isNone(resourceHash.type), { id: 'ds.serializer.type-is-undefined' }); var modelName = undefined, usedLookup = undefined; if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { modelName = this.modelNameFromPayloadType(resourceHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type); usedLookup = 'modelNameFromPayloadType'; if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a resource. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.json-api-serializer.deprecated-model-name-for-resource', until: '3.0.0' }); modelName = deprecatedModelNameLookup; usedLookup = 'modelNameFromPayloadKey'; } } else { modelName = this.modelNameFromPayloadKey(resourceHash.type); usedLookup = 'modelNameFromPayloadKey'; } if (!this.store._hasModelFor(modelName)) { (0, _emberDataPrivateDebug.warn)(this.warnMessageNoModelForType(modelName, resourceHash.type, usedLookup), false, { id: 'ds.serializer.model-for-type-missing' }); return null; } var modelClass = this.store.modelFor(modelName); var serializer = this.store.serializerFor(modelName); var _serializer$normalize = serializer.normalize(modelClass, resourceHash); var data = _serializer$normalize.data; return data; }, /** @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function (store, payload) { var normalizedPayload = this._normalizeDocumentHelper(payload); if ((0, _emberDataPrivateFeatures.default)('ds-pushpayload-return')) { return store.push(normalizedPayload); } else { store.push(normalizedPayload); } }, /** @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var normalizedPayload = this._normalizeDocumentHelper(payload); return normalizedPayload; }, normalizeQueryRecordResponse: function () { var normalized = this._super.apply(this, arguments); (0, _emberDataPrivateDebug.assert)('Expected the primary data returned by the serializer for a `queryRecord` response to be a single object but instead it was an array.', !Array.isArray(normalized.data), { id: 'ds.serializer.json-api.queryRecord-array-response' }); return normalized; }, /** @method extractAttributes @param {DS.Model} modelClass @param {Object} resourceHash @return {Object} */ extractAttributes: function (modelClass, resourceHash) { var _this = this; var attributes = {}; if (resourceHash.attributes) { modelClass.eachAttribute(function (key) { var attributeKey = _this.keyForAttribute(key, 'deserialize'); if (resourceHash.attributes[attributeKey] !== undefined) { attributes[key] = resourceHash.attributes[attributeKey]; } }); } return attributes; }, /** @method extractRelationship @param {Object} relationshipHash @return {Object} */ extractRelationship: function (relationshipHash) { if (_ember.default.typeOf(relationshipHash.data) === 'object') { relationshipHash.data = this._normalizeRelationshipDataHelper(relationshipHash.data); } if (Array.isArray(relationshipHash.data)) { var ret = new Array(relationshipHash.data.length); for (var i = 0; i < relationshipHash.data.length; i++) { var data = relationshipHash.data[i]; ret[i] = this._normalizeRelationshipDataHelper(data); } relationshipHash.data = ret; } return relationshipHash; }, /** @method extractRelationships @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractRelationships: function (modelClass, resourceHash) { var _this2 = this; var relationships = {}; if (resourceHash.relationships) { modelClass.eachRelationship(function (key, relationshipMeta) { var relationshipKey = _this2.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); if (resourceHash.relationships[relationshipKey] !== undefined) { var relationshipHash = resourceHash.relationships[relationshipKey]; relationships[key] = _this2.extractRelationship(relationshipHash); } }); } return relationships; }, /** @method _extractType @param {DS.Model} modelClass @param {Object} resourceHash @return {String} @private */ _extractType: function (modelClass, resourceHash) { if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { var modelName = this.modelNameFromPayloadType(resourceHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.json-api-serializer.deprecated-model-name-for-polymorphic-type', until: '3.0.0' }); modelName = deprecatedModelNameLookup; } return modelName; } else { return this.modelNameFromPayloadKey(resourceHash.type); } }, /** @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ // TODO @deprecated Use modelNameFromPayloadType instead modelNameFromPayloadKey: function (key) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(key)); }, /** @method payloadKeyFromModelName @param {String} modelName @return {String} */ // TODO @deprecated Use payloadTypeFromModelName instead payloadKeyFromModelName: function (modelName) { return (0, _emberInflector.pluralize)(modelName); }, /** @method normalize @param {DS.Model} modelClass @param {Object} resourceHash the resource hash from the adapter @return {Object} the normalized resource hash */ normalize: function (modelClass, resourceHash) { if (resourceHash.attributes) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.attributes); } if (resourceHash.relationships) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.relationships); } var data = { id: this.extractId(modelClass, resourceHash), type: this._extractType(modelClass, resourceHash), attributes: this.extractAttributes(modelClass, resourceHash), relationships: this.extractRelationships(modelClass, resourceHash) }; this.applyTransforms(modelClass, data.attributes); return { data: data }; }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. By default `JSONAPISerializer` follows the format used on the examples of http://jsonapi.org/format and uses dashes as the word separator in the JSON attribute keys. This behaviour can be easily customized by extending this method. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.dasherize(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @param {String} method @return {String} normalized key */ keyForAttribute: function (key, method) { return dasherize(key); }, /** `keyForRelationship` can be used to define a custom key when serializing and deserializing relationship properties. By default `JSONAPISerializer` follows the format used on the examples of http://jsonapi.org/format and uses dashes as word separators in relationship properties. This behaviour can be easily customized by extending this method. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ keyForRelationship: function(key, relationship, method) { return Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForRelationship: function (key, typeClass, method) { return dasherize(key); }, /** @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function (snapshot, options) { var data = this._super.apply(this, arguments); var payloadType = undefined; if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { payloadType = this.payloadTypeFromModelName(snapshot.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(snapshot.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { (0, _emberDataPrivateDebug.deprecate)("You used payloadKeyFromModelName to customize how a type is serialized. Use payloadTypeFromModelName instead.", false, { id: 'ds.json-api-serializer.deprecated-payload-type-for-model', until: '3.0.0' }); payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(snapshot.modelName); } data.type = payloadType; return { data: data }; }, /** @method serializeAttribute @param {DS.Snapshot} snapshot @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function (snapshot, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { json.attributes = json.attributes || {}; var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value, attribute.options); } var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key) { payloadKey = this.keyForAttribute(key, 'serialize'); } json.attributes[payloadKey] = value; } }, /** @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function (snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsTo = snapshot.belongsTo(key); if (belongsTo !== undefined) { json.relationships = json.relationships || {}; var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key) { payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize'); } var data = null; if (belongsTo) { var payloadType = undefined; if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { payloadType = this.payloadTypeFromModelName(belongsTo.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(belongsTo.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { (0, _emberDataPrivateDebug.deprecate)("You used payloadKeyFromModelName to serialize type for belongs-to relationship. Use payloadTypeFromModelName instead.", false, { id: 'ds.json-api-serializer.deprecated-payload-type-for-belongs-to', until: '3.0.0' }); payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(belongsTo.modelName); } data = { type: payloadType, id: belongsTo.id }; } json.relationships[payloadKey] = { data: data }; } } }, /** @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function (snapshot, json, relationship) { var key = relationship.key; var shouldSerializeHasMany = '_shouldSerializeHasMany'; if ((0, _emberDataPrivateFeatures.default)("ds-check-should-serialize-relationships")) { shouldSerializeHasMany = 'shouldSerializeHasMany'; } if (this[shouldSerializeHasMany](snapshot, key, relationship)) { var hasMany = snapshot.hasMany(key); if (hasMany !== undefined) { json.relationships = json.relationships || {}; var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize'); } var data = new Array(hasMany.length); for (var i = 0; i < hasMany.length; i++) { var item = hasMany[i]; var payloadType = undefined; if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { payloadType = this.payloadTypeFromModelName(item.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(item.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { (0, _emberDataPrivateDebug.deprecate)("You used payloadKeyFromModelName to serialize type for belongs-to relationship. Use payloadTypeFromModelName instead.", false, { id: 'ds.json-api-serializer.deprecated-payload-type-for-has-many', until: '3.0.0' }); payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(item.modelName); } data[i] = { type: payloadType, id: item.id }; } json.relationships[payloadKey] = { data: data }; } } } }); if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { JSONAPISerializer.reopen({ /** `modelNameFromPayloadType` can be used to change the mapping for a DS model name, taken from the value in the payload. Say your API namespaces the type of a model and returns the following payload for the `post` model: ```javascript // GET /api/posts/1 { "data": { "id": 1, "type: "api::v1::post" } } ``` By overwriting `modelNameFromPayloadType` you can specify that the `posr` model should be used: ```app/serializers/application.js import DS from "ember-data"; export default DS.JSONAPISerializer.extend({ modelNameFromPayloadType(payloadType) { return payloadType.replace('api::v1::', ''); } }); ``` By default the modelName for a model is its singularized name in dasherized form. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadType` for this purpose. Also take a look at [payloadTypeFromModelName](#method_payloadTypeFromModelName) to customize how the type of a record should be serialized. @method modelNameFromPayloadType @public @param {String} payloadType type from payload @return {String} modelName */ modelNameFromPayloadType: function (type) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(type)); }, /** `payloadTypeFromModelName` can be used to change the mapping for the type in the payload, taken from the model name. Say your API namespaces the type of a model and expects the following payload when you update the `post` model: ```javascript // POST /api/posts/1 { "data": { "id": 1, "type": "api::v1::post" } } ``` By overwriting `payloadTypeFromModelName` you can specify that the namespaces model name for the `post` should be used: ```app/serializers/application.js import DS from "ember-data"; export default JSONAPISerializer.extend({ payloadTypeFromModelName(modelName) { return "api::v1::" + modelName; } }); ``` By default the payload type is the pluralized model name. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `payloadTypeFromModelName` for this purpose. Also take a look at [modelNameFromPayloadType](#method_modelNameFromPayloadType) to customize how the model name from should be mapped from the payload. @method payloadTypeFromModelName @public @param {String} modelname modelName from the record @return {String} payloadType */ payloadTypeFromModelName: function (modelName) { return (0, _emberInflector.pluralize)(modelName); }, _hasCustomModelNameFromPayloadKey: function () { return this.modelNameFromPayloadKey !== JSONAPISerializer.prototype.modelNameFromPayloadKey; }, _hasCustomPayloadKeyFromModelName: function () { return this.payloadKeyFromModelName !== JSONAPISerializer.prototype.payloadKeyFromModelName; } }); } (0, _emberDataPrivateDebug.runInDebug)(function () { JSONAPISerializer.reopen({ willMergeMixin: function (props) { (0, _emberDataPrivateDebug.warn)('The JSONAPISerializer does not work with the EmbeddedRecordsMixin because the JSON API spec does not describe how to format embedded resources.', !props.isEmbeddedRecordsMixin, { id: 'ds.serializer.embedded-records-mixin-not-supported' }); }, warnMessageForUndefinedType: function () { return 'Encountered a resource object with an undefined type (resolved resource using ' + this.constructor.toString() + ')'; }, warnMessageNoModelForType: function (modelName, originalType, usedLookup) { return 'Encountered a resource object with type "' + originalType + '", but no model was found for model name "' + modelName + '" (resolved model name using \'' + this.constructor.toString() + '.' + usedLookup + '("' + originalType + '")).'; } }); }); exports.default = JSONAPISerializer; }); /** @module ember-data */ define('ember-data/serializers/json', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializer', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/utils', 'ember-data/-private/features', 'ember-data/adapters/errors'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializer, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateUtils, _emberDataPrivateFeatures, _emberDataAdaptersErrors) { 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); } } var get = _ember.default.get; var isNone = _ember.default.isNone; var assign = _ember.default.assign || _ember.default.merge; /** Ember Data 2.0 Serializer: 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. By default, Ember Data uses and recommends the `JSONAPISerializer`. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. For example, given the following `User` model and JSON payload: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ friends: DS.hasMany('user'), house: DS.belongsTo('location'), name: DS.attr('string') }); ``` ```js { id: 1, name: 'Sebastian', friends: [3, 4], links: { house: '/houses/lefkada' } } ``` `JSONSerializer` will normalize the JSON payload to the JSON API format that the Ember Data store expects. You can customize how JSONSerializer processes its payload by passing options in the `attrs` hash or by subclassing the `JSONSerializer` and overriding hooks: - To customize how a single record is normalized, use the `normalize` hook. - To customize how `JSONSerializer` normalizes the whole server response, use the `normalizeResponse` hook. - To customize how `JSONSerializer` normalizes a specific response from the server, use one of the many specific `normalizeResponse` hooks. - To customize how `JSONSerializer` normalizes your id, attributes or relationships, use the `extractId`, `extractAttributes` and `extractRelationships` hooks. The `JSONSerializer` normalization process follows these steps: - `normalizeResponse` - entry method to the serializer. - `normalizeCreateRecordResponse` - a `normalizeResponse` for a specific operation is called. - `normalizeSingleResponse`|`normalizeArrayResponse` - for methods like `createRecord` we expect a single record back, while for methods like `findAll` we expect multiple methods back. - `normalize` - `normalizeArray` iterates and calls `normalize` for each of its records while `normalizeSingle` calls it once. This is the method you most likely want to subclass. - `extractId` | `extractAttributes` | `extractRelationships` - `normalize` delegates to these methods to turn the record payload into the JSON API format. @class JSONSerializer @namespace DS @extends DS.Serializer */ var JSONSerializer = _emberDataSerializer.default.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 ```app/serializers/application.js import DS from 'ember-data'; export default 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 property `key` can also be used to designate the attribute's key on the response payload. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string'), admin: DS.attr('boolean') }); ``` ```app/serializers/person.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ attrs: { admin: 'is_admin', occupation: { key: 'career' } } }); ``` You can also remove attributes by setting the `serialize` key to `false` in your mapping object. Example ```app/serializers/person.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ attrs: { admin: { serialize: false }, occupation: { key: 'career' } } }); ``` When serialized: ```javascript { "firstName": "Harry", "lastName": "Houdini", "career": "magician" } ``` Note that the `admin` is now not included in the payload. @property attrs @type {Object} */ mergedProperties: ['attrs'], /** 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 {DS.Model} typeClass @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function (typeClass, data) { var _this = this; var attributes = get(typeClass, 'attributes'); typeClass.eachTransformedAttribute(function (key, typeClass) { if (data[key] === undefined) { return; } var transform = _this.transformFor(typeClass); var transformMeta = attributes.get(key); data[key] = transform.deserialize(data[key], transformMeta.options); }); return data; }, /** The `normalizeResponse` method is used to normalize a payload from the server to a JSON-API Document. http://jsonapi.org/format/#document-structure This method delegates to a more specific normalize method based on the `requestType`. To override this method with a custom one, make sure to call `return this._super(store, primaryModelClass, payload, id, requestType)` with your pre-processed data. Here's an example of using `normalizeResponse` manually: ```javascript socket.on('message', function(message) { var data = message.data; var modelClass = store.modelFor(data.modelName); var serializer = store.serializerFor(data.modelName); var normalized = serializer.normalizeSingleResponse(store, modelClass, data, data.id); store.push(normalized); }); ``` @since 1.13.0 @method normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeResponse: function (store, primaryModelClass, payload, id, requestType) { switch (requestType) { case 'findRecord': return this.normalizeFindRecordResponse.apply(this, arguments); case 'queryRecord': return this.normalizeQueryRecordResponse.apply(this, arguments); case 'findAll': return this.normalizeFindAllResponse.apply(this, arguments); case 'findBelongsTo': return this.normalizeFindBelongsToResponse.apply(this, arguments); case 'findHasMany': return this.normalizeFindHasManyResponse.apply(this, arguments); case 'findMany': return this.normalizeFindManyResponse.apply(this, arguments); case 'query': return this.normalizeQueryResponse.apply(this, arguments); case 'createRecord': return this.normalizeCreateRecordResponse.apply(this, arguments); case 'deleteRecord': return this.normalizeDeleteRecordResponse.apply(this, arguments); case 'updateRecord': return this.normalizeUpdateRecordResponse.apply(this, arguments); } }, /** @since 1.13.0 @method normalizeFindRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeQueryRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeQueryRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindAllResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindAllResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindBelongsToResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindBelongsToResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindHasManyResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindHasManyResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindManyResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindManyResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeQueryResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeQueryResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeCreateRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeCreateRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeDeleteRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeDeleteRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeUpdateRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeUpdateRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeSaveResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeSaveResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeSingleResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeSingleResponse: function (store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true); }, /** @since 1.13.0 @method normalizeArrayResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeArrayResponse: function (store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, false); }, /** @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { (0, _emberDataPrivateDebug.assert)('The `meta` returned from `extractMeta` has to be an object, not "' + _ember.default.typeOf(meta) + '".', _ember.default.typeOf(meta) === 'object'); documentHash.meta = meta; } if (isSingle) { var _normalize = this.normalize(primaryModelClass, payload); var data = _normalize.data; var included = _normalize.included; documentHash.data = data; if (included) { documentHash.included = included; } } else { var ret = new Array(payload.length); for (var i = 0, l = payload.length; i < l; i++) { var item = payload[i]; var _normalize2 = this.normalize(primaryModelClass, item); var data = _normalize2.data; var included = _normalize2.included; if (included) { var _documentHash$included; (_documentHash$included = documentHash.included).push.apply(_documentHash$included, _toConsumableArray(included)); } ret[i] = data; } documentHash.data = ret; } return documentHash; }, /** 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 ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ normalize: function(typeClass, hash) { var fields = Ember.get(typeClass, '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 {DS.Model} typeClass @param {Object} hash @return {Object} */ normalize: function (modelClass, resourceHash) { var data = null; if (resourceHash) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash); if (_ember.default.typeOf(resourceHash.links) === 'object') { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.links); } data = { id: this.extractId(modelClass, resourceHash), type: modelClass.modelName, attributes: this.extractAttributes(modelClass, resourceHash), relationships: this.extractRelationships(modelClass, resourceHash) }; this.applyTransforms(modelClass, data.attributes); } return { data: data }; }, /** Returns the resource's ID. @method extractId @param {Object} modelClass @param {Object} resourceHash @return {String} */ extractId: function (modelClass, resourceHash) { var primaryKey = get(this, 'primaryKey'); var id = resourceHash[primaryKey]; return (0, _emberDataPrivateSystemCoerceId.default)(id); }, /** Returns the resource's attributes formatted as a JSON-API "attributes object". http://jsonapi.org/format/#document-resource-object-attributes @method extractAttributes @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractAttributes: function (modelClass, resourceHash) { var _this2 = this; var attributeKey; var attributes = {}; modelClass.eachAttribute(function (key) { attributeKey = _this2.keyForAttribute(key, 'deserialize'); if (resourceHash[attributeKey] !== undefined) { attributes[key] = resourceHash[attributeKey]; } }); return attributes; }, /** Returns a relationship formatted as a JSON-API "relationship object". http://jsonapi.org/format/#document-resource-object-relationships @method extractRelationship @param {Object} relationshipModelName @param {Object} relationshipHash @return {Object} */ extractRelationship: function (relationshipModelName, relationshipHash) { if (_ember.default.isNone(relationshipHash)) { return null; } /* When `relationshipHash` is an object it usually means that the relationship is polymorphic. It could however also be embedded resources that the EmbeddedRecordsMixin has be able to process. */ if (_ember.default.typeOf(relationshipHash) === 'object') { if (relationshipHash.id) { relationshipHash.id = (0, _emberDataPrivateSystemCoerceId.default)(relationshipHash.id); } var modelClass = this.store.modelFor(relationshipModelName); if (relationshipHash.type && !(0, _emberDataPrivateUtils.modelHasAttributeOrRelationshipNamedType)(modelClass)) { if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { var modelName = this.modelNameFromPayloadType(relationshipHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You used modelNameFromPayloadKey to customize how a type is normalized. Use modelNameFromPayloadType instead", false, { id: 'ds.json-serializer.deprecated-type-for-polymorphic-relationship', until: '3.0.0' }); modelName = deprecatedModelNameLookup; } relationshipHash.type = modelName; } else { relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type); } } return relationshipHash; } return { id: (0, _emberDataPrivateSystemCoerceId.default)(relationshipHash), type: relationshipModelName }; }, /** Returns a polymorphic relationship formatted as a JSON-API "relationship object". http://jsonapi.org/format/#document-resource-object-relationships `relationshipOptions` is a hash which contains more information about the polymorphic relationship which should be extracted: - `resourceHash` complete hash of the resource the relationship should be extracted from - `relationshipKey` key under which the value for the relationship is extracted from the resourceHash - `relationshipMeta` meta information about the relationship @method extractPolymorphicRelationship @param {Object} relationshipModelName @param {Object} relationshipHash @param {Object} relationshipOptions @return {Object} */ extractPolymorphicRelationship: function (relationshipModelName, relationshipHash, relationshipOptions) { return this.extractRelationship(relationshipModelName, relationshipHash); }, /** Returns the resource's relationships formatted as a JSON-API "relationships object". http://jsonapi.org/format/#document-resource-object-relationships @method extractRelationships @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractRelationships: function (modelClass, resourceHash) { var _this3 = this; var relationships = {}; modelClass.eachRelationship(function (key, relationshipMeta) { var relationship = null; var relationshipKey = _this3.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); if (resourceHash[relationshipKey] !== undefined) { var data = null; var relationshipHash = resourceHash[relationshipKey]; if (relationshipMeta.kind === 'belongsTo') { if (relationshipMeta.options.polymorphic) { // extracting a polymorphic belongsTo may need more information // than the type and the hash (which might only be an id) for the // relationship, hence we pass the key, resource and // relationshipMeta too data = _this3.extractPolymorphicRelationship(relationshipMeta.type, relationshipHash, { key: key, resourceHash: resourceHash, relationshipMeta: relationshipMeta }); } else { data = _this3.extractRelationship(relationshipMeta.type, relationshipHash); } } else if (relationshipMeta.kind === 'hasMany') { if (!_ember.default.isNone(relationshipHash)) { data = new Array(relationshipHash.length); for (var i = 0, l = relationshipHash.length; i < l; i++) { var item = relationshipHash[i]; data[i] = _this3.extractRelationship(relationshipMeta.type, item); } } } relationship = { data: data }; } var linkKey = _this3.keyForLink(key, relationshipMeta.kind); if (resourceHash.links && resourceHash.links[linkKey] !== undefined) { var related = resourceHash.links[linkKey]; relationship = relationship || {}; relationship.links = { related: related }; } if (relationship) { relationships[key] = relationship; } }); return relationships; }, /** @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ // TODO @deprecated Use modelNameFromPayloadType instead modelNameFromPayloadKey: function (key) { return (0, _emberDataPrivateSystemNormalizeModelName.default)(key); }, /** @method normalizeAttributes @private */ normalizeAttributes: function (typeClass, hash) { var _this4 = this; var payloadKey; if (this.keyForAttribute) { typeClass.eachAttribute(function (key) { payloadKey = _this4.keyForAttribute(key, 'deserialize'); if (key === payloadKey) { return; } if (hash[payloadKey] === undefined) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function (typeClass, hash) { var _this5 = this; var payloadKey; if (this.keyForRelationship) { typeClass.eachRelationship(function (key, relationship) { payloadKey = _this5.keyForRelationship(key, relationship.kind, 'deserialize'); if (key === payloadKey) { return; } if (hash[payloadKey] === undefined) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }); } }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function (modelClass, hash) { var attrs = get(this, 'attrs'); var normalizedKey, payloadKey, key; if (attrs) { for (key in attrs) { normalizedKey = payloadKey = this._getMappedKey(key, modelClass); if (hash[payloadKey] === undefined) { continue; } if (get(modelClass, 'attributes').has(key)) { normalizedKey = this.keyForAttribute(key); } if (get(modelClass, 'relationshipsByName').has(key)) { normalizedKey = this.keyForRelationship(key); } if (payloadKey !== normalizedKey) { hash[normalizedKey] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** Looks up the property key that was set by the custom `attr` mapping passed to the serializer. @method _getMappedKey @private @param {String} key @return {String} key */ _getMappedKey: function (key, modelClass) { (0, _emberDataPrivateDebug.warn)('There is no attribute or relationship with the name `' + key + '` on `' + modelClass.modelName + '`. Check your serializers attrs hash.', get(modelClass, 'attributes').has(key) || get(modelClass, 'relationshipsByName').has(key), { id: 'ds.serializer.no-mapped-attrs-key' }); var attrs = get(this, 'attrs'); var mappedKey; if (attrs && attrs[key]) { mappedKey = attrs[key]; //We need to account for both the { title: 'post_title' } and //{ title: { key: 'post_title' }} forms if (mappedKey.key) { mappedKey = mappedKey.key; } if (typeof mappedKey === 'string') { key = mappedKey; } } return key; }, /** Check attrs.key.serialize property to inform if the `key` can be serialized @method _canSerialize @private @param {String} key @return {boolean} true if the key can be serialized */ _canSerialize: function (key) { var attrs = get(this, 'attrs'); return !attrs || !attrs[key] || attrs[key].serialize !== false; }, /** When attrs.key.serialize is set to true then it takes priority over the other checks and the related attribute/relationship will be serialized @method _mustSerialize @private @param {String} key @return {boolean} true if the key must be serialized */ _mustSerialize: function (key) { var attrs = get(this, 'attrs'); return attrs && attrs[key] && attrs[key].serialize === true; }, /** Check if the given hasMany relationship should be serialized @method shouldSerializeHasMany @param {DS.Snapshot} snapshot @param {String} key @param {String} relationshipType @return {boolean} true if the hasMany relationship should be serialized */ shouldSerializeHasMany: function (snapshot, key, relationship) { if (this._shouldSerializeHasMany !== JSONSerializer.prototype._shouldSerializeHasMany) { (0, _emberDataPrivateDebug.deprecate)('The private method _shouldSerializeHasMany has been promoted to the public API. Please remove the underscore to use the public shouldSerializeHasMany method.', false, { id: 'ds.serializer.private-should-serialize-has-many', until: '3.0.0' }); } return this._shouldSerializeHasMany(snapshot, key, relationship); }, /** Check if the given hasMany relationship should be serialized @method _shouldSerializeHasMany @private @param {DS.Snapshot} snapshot @param {String} key @param {String} relationshipType @return {boolean} true if the hasMany relationship should be serialized */ _shouldSerializeHasMany: function (snapshot, key, relationship) { var relationshipType = snapshot.type.determineRelationshipType(relationship, this.store); if (this._mustSerialize(key)) { return true; } return this._canSerialize(key) && (relationshipType === 'manyToNone' || relationshipType === 'manyToMany'); }, // 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: ```app/models/comment.js import DS from 'ember-data'; export default 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. ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.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. ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.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. ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function (snapshot, options) { var _this6 = this; var json = {}; if (options && options.includeId) { var id = snapshot.id; if (id) { json[get(this, 'primaryKey')] = id; } } snapshot.eachAttribute(function (key, attribute) { _this6.serializeAttribute(snapshot, json, key, attribute); }); snapshot.eachRelationship(function (key, relationship) { if (relationship.kind === 'belongsTo') { _this6.serializeBelongsTo(snapshot, json, relationship); } else if (relationship.kind === 'hasMany') { _this6.serializeHasMany(snapshot, json, relationship); } }); return json; }, /** You can use this method to customize how a serialized record is added to the complete JSON hash to be sent to the server. By default the JSON Serializer does not namespace the payload and just sends the raw serialized JSON object. If your server expects namespaced keys, you should consider using the RESTSerializer. Otherwise you can override this method to customize how the record is added to the hash. The hash property should be modified by reference. For example, your server may expect underscored root objects. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, snapshot, options) { var root = Ember.String.decamelize(type.modelName); data[root] = this.serialize(snapshot, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function (hash, typeClass, snapshot, options) { assign(hash, this.serialize(snapshot, options)); }, /** `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: ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeAttribute: function(snapshot, json, key, attributes) { json.attributes = json.attributes || {}; this._super(snapshot, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Snapshot} snapshot @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function (snapshot, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value, attribute.options); } // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForAttribute) { payloadKey = this.keyForAttribute(key, 'serialize'); } json[payloadKey] = value; } }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeBelongsTo: function(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.record.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function (snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsToId = snapshot.belongsTo(key, { id: true }); // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "belongsTo", "serialize"); } //Need to check whether the id is there for new&async records if (isNone(belongsToId)) { json[payloadKey] = null; } else { json[payloadKey] = belongsToId; } if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeHasMany: function(snapshot, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function (snapshot, json, relationship) { var key = relationship.key; var shouldSerializeHasMany = '_shouldSerializeHasMany'; if ((0, _emberDataPrivateFeatures.default)("ds-check-should-serialize-relationships")) { shouldSerializeHasMany = 'shouldSerializeHasMany'; } if (this[shouldSerializeHasMany](snapshot, key, relationship)) { var hasMany = snapshot.hasMany(key, { ids: true }); if (hasMany !== undefined) { // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "hasMany", "serialize"); } json[payloadKey] = hasMany; // 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 ```app/serializers/comment.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializePolymorphicType: function(snapshot, json, relationship) { var key = relationship.key, belongsTo = snapshot.belongsTo(key); key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; if (Ember.isNone(belongsTo)) { json[key + "_type"] = null; } else { json[key + "_type"] = belongsTo.modelName; } } }); ``` @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: _ember.default.K, /** `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 ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractMeta: function(store, typeClass, payload) { if (payload && payload.hasOwnProperty('_pagination')) { let meta = payload._pagination; delete payload._pagination; return meta; } } }); ``` @method extractMeta @param {DS.Store} store @param {DS.Model} modelClass @param {Object} payload */ extractMeta: function (store, modelClass, payload) { if (payload && payload['meta'] !== undefined) { var meta = payload.meta; delete payload.meta; return meta; } }, /** `extractErrors` is used to extract model errors when a call to `DS.Model#save` fails with an `InvalidError`. By default Ember Data expects error information to be located on the `errors` property of the payload object. This serializer expects this `errors` object to be an Array similar to the following, compliant with the JSON-API specification: ```js { "errors": [ { "detail": "This username is already taken!", "source": { "pointer": "data/attributes/username" } }, { "detail": "Doesn't look like a valid email.", "source": { "pointer": "data/attributes/email" } } ] } ``` The key `detail` provides a textual description of the problem. Alternatively, the key `title` can be used for the same purpose. The nested keys `source.pointer` detail which specific element of the request data was invalid. Note that JSON-API also allows for object-level errors to be placed in an object with pointer `data`, signifying that the problem cannot be traced to a specific attribute: ```javascript { "errors": [ { "detail": "Some generic non property error message", "source": { "pointer": "data" } } ] } ``` When turn into a `DS.Errors` object, you can read these errors through the property `base`: ```handlebars {{#each model.errors.base as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` Example of alternative implementation, overriding the default behavior to deal with a different format of errors: ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractErrors: function(store, typeClass, payload, id) { if (payload && typeof payload === 'object' && payload._problems) { payload = payload._problems; this.normalizeErrors(typeClass, payload); } return payload; } }); ``` @method extractErrors @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @return {Object} json The deserialized errors */ extractErrors: function (store, typeClass, payload, id) { var _this7 = this; if (payload && typeof payload === 'object' && payload.errors) { payload = (0, _emberDataAdaptersErrors.errorsArrayToHash)(payload.errors); this.normalizeUsingDeclaredMapping(typeClass, payload); typeClass.eachAttribute(function (name) { var key = _this7.keyForAttribute(name, 'deserialize'); if (key !== name && payload[key] !== undefined) { payload[name] = payload[key]; delete payload[key]; } }); typeClass.eachRelationship(function (name) { var key = _this7.keyForRelationship(name, 'deserialize'); if (key !== name && payload[key] !== undefined) { payload[name] = payload[key]; delete payload[key]; } }); } return payload; }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @param {String} method @return {String} normalized key */ keyForAttribute: function (key, method) { return key; }, /** `keyForRelationship` can be used to define a custom key when serializing and deserializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship, method) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForRelationship: function (key, typeClass, method) { return key; }, /** `keyForLink` can be used to define a custom key when deserializing link properties. @method keyForLink @param {String} key @param {String} kind `belongsTo` or `hasMany` @return {String} normalized key */ keyForLink: function (key, kind) { return key; }, // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function (attributeType, skipAssertion) { var transform = (0, _emberDataPrivateUtils.getOwner)(this).lookup('transform:' + attributeType); (0, _emberDataPrivateDebug.assert)("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform); return transform; } }); if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { JSONSerializer.reopen({ /** @method modelNameFromPayloadType @public @param {String} type @return {String} the model's modelName */ modelNameFromPayloadType: function (type) { return (0, _emberDataPrivateSystemNormalizeModelName.default)(type); }, _hasCustomModelNameFromPayloadKey: function () { return this.modelNameFromPayloadKey !== JSONSerializer.prototype.modelNameFromPayloadKey; } }); } exports.default = JSONSerializer; }); define("ember-data/serializers/rest", ["exports", "ember", "ember-data/-private/debug", "ember-data/serializers/json", "ember-data/-private/system/normalize-model-name", "ember-inflector", "ember-data/-private/system/coerce-id", "ember-data/-private/utils", "ember-data/-private/features"], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializersJson, _emberDataPrivateSystemNormalizeModelName, _emberInflector, _emberDataPrivateSystemCoerceId, _emberDataPrivateUtils, _emberDataPrivateFeatures) { 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); } } var camelize = _ember.default.String.camelize; /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method. 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 define 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 Firebase, 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. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, the kind of relationship (`hasMany` or `belongsTo`) as the second parameter, and the method (`serialize` or `deserialize`) as the third parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ var RESTSerializer = _emberDataSerializersJson.default.extend({ /** `keyForPolymorphicType` can be used to define a custom key when serializing and deserializing a polymorphic type. By default, the returned key is `${key}Type`. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForPolymorphicType: function(key, relationship) { var relationshipKey = this.keyForRelationship(key); return 'type-' + relationshipKey; } }); ``` @method keyForPolymorphicType @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForPolymorphicType: function (key, typeClass, method) { var relationshipKey = this.keyForRelationship(key); return relationshipKey + "Type"; }, /** 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. You will only need to implement `normalize` and manipulate the payload as desired. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ normalize(model, hash, prop) { if (prop === 'comments') { hash.id = hash._id; delete hash._id; } return this._super(...arguments); } }); ``` On each call to the `normalize` method, the third parameter (`prop`) is always one of the keys that were in the original payload or in the result of another normalization as `normalizeResponse`. @method normalize @param {DS.Model} modelClass @param {Object} resourceHash @param {String} prop @return {Object} */ normalize: function (modelClass, resourceHash, prop) { if (this.normalizeHash && this.normalizeHash[prop]) { (0, _emberDataPrivateDebug.deprecate)('`RESTSerializer.normalizeHash` has been deprecated. Please use `serializer.normalize` to modify the payload of single resources.', false, { id: 'ds.serializer.normalize-hash-deprecated', until: '3.0.0' }); this.normalizeHash[prop](resourceHash); } return this._super(modelClass, resourceHash); }, /** Normalizes an array of resource payloads and returns a JSON-API Document with primary data and, if any, included data as `{ data, included }`. @method _normalizeArray @param {DS.Store} store @param {String} modelName @param {Object} arrayHash @param {String} prop @return {Object} @private */ _normalizeArray: function (store, modelName, arrayHash, prop) { var _this = this; var documentHash = { data: [], included: [] }; var modelClass = store.modelFor(modelName); var serializer = store.serializerFor(modelName); _ember.default.makeArray(arrayHash).forEach(function (hash) { var _normalizePolymorphicRecord = _this._normalizePolymorphicRecord(store, hash, prop, modelClass, serializer); var data = _normalizePolymorphicRecord.data; var included = _normalizePolymorphicRecord.included; documentHash.data.push(data); if (included) { var _documentHash$included; (_documentHash$included = documentHash.included).push.apply(_documentHash$included, _toConsumableArray(included)); } }); return documentHash; }, _normalizePolymorphicRecord: function (store, hash, prop, primaryModelClass, primarySerializer) { var serializer = primarySerializer; var modelClass = primaryModelClass; var primaryHasTypeAttribute = (0, _emberDataPrivateUtils.modelHasAttributeOrRelationshipNamedType)(primaryModelClass); if (!primaryHasTypeAttribute && hash.type) { // Support polymorphic records in async relationships var modelName = undefined; if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { modelName = this.modelNameFromPayloadType(hash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(hash.type); if (modelName !== deprecatedModelNameLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This is has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.rest-serializer.deprecated-model-name-for-polymorphic-type', until: '3.0.0' }); modelName = deprecatedModelNameLookup; } } else { modelName = this.modelNameFromPayloadKey(hash.type); } if (store._hasModelFor(modelName)) { serializer = store.serializerFor(modelName); modelClass = store.modelFor(modelName); } } return serializer.normalize(modelClass, hash, prop); }, /* @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { (0, _emberDataPrivateDebug.assert)('The `meta` returned from `extractMeta` has to be an object, not "' + _ember.default.typeOf(meta) + '".', _ember.default.typeOf(meta) === 'object'); documentHash.meta = meta; } var keys = Object.keys(payload); for (var i = 0, _length = keys.length; i < _length; i++) { var prop = keys[i]; var modelName = prop; var forcedSecondary = false; /* If you want to provide sideloaded records of the same type that the primary data you can do that by prefixing the key with `_`. Example ``` { users: [ { id: 1, title: 'Tom', manager: 3 }, { id: 2, title: 'Yehuda', manager: 3 } ], _users: [ { id: 3, title: 'Tomster' } ] } ``` This forces `_users` to be added to `included` instead of `data`. */ if (prop.charAt(0) === '_') { forcedSecondary = true; modelName = prop.substr(1); } var typeName = this.modelNameFromPayloadKey(modelName); if (!store.modelFactoryFor(typeName)) { (0, _emberDataPrivateDebug.warn)(this.warnMessageNoModelForKey(modelName, typeName), false, { id: 'ds.serializer.model-for-key-missing' }); continue; } var isPrimary = !forcedSecondary && this.isPrimaryType(store, typeName, primaryModelClass); var value = payload[prop]; if (value === null) { continue; } (0, _emberDataPrivateDebug.runInDebug)(function () { var isQueryRecordAnArray = requestType === 'queryRecord' && isPrimary && Array.isArray(value); var message = "The adapter returned an array for the primary data of a `queryRecord` response. This is deprecated as `queryRecord` should return a single record."; (0, _emberDataPrivateDebug.deprecate)(message, !isQueryRecordAnArray, { id: 'ds.serializer.rest.queryRecord-array-response', until: '3.0' }); }); /* Support primary data as an object instead of an array. Example ``` { user: { id: 1, title: 'Tom', manager: 3 } } ``` */ if (isPrimary && _ember.default.typeOf(value) !== 'array') { var _normalizePolymorphicRecord2 = this._normalizePolymorphicRecord(store, value, prop, primaryModelClass, this); var _data = _normalizePolymorphicRecord2.data; var _included = _normalizePolymorphicRecord2.included; documentHash.data = _data; if (_included) { var _documentHash$included2; (_documentHash$included2 = documentHash.included).push.apply(_documentHash$included2, _toConsumableArray(_included)); } continue; } var _normalizeArray = this._normalizeArray(store, typeName, value, prop); var data = _normalizeArray.data; var included = _normalizeArray.included; if (included) { var _documentHash$included3; (_documentHash$included3 = documentHash.included).push.apply(_documentHash$included3, _toConsumableArray(included)); } if (isSingle) { data.forEach(function (resource) { /* Figures out if this is the primary record or not. It's either: 1. The record with the same ID as the original request 2. If it's a newly created record without an ID, the first record in the array */ var isUpdatedRecord = isPrimary && (0, _emberDataPrivateSystemCoerceId.default)(resource.id) === id; var isFirstCreatedRecord = isPrimary && !id && !documentHash.data; if (isFirstCreatedRecord || isUpdatedRecord) { documentHash.data = resource; } else { documentHash.included.push(resource); } }); } else { if (isPrimary) { documentHash.data = data; } else { if (data) { var _documentHash$included4; (_documentHash$included4 = documentHash.included).push.apply(_documentHash$included4, _toConsumableArray(data)); } } } } return documentHash; }, isPrimaryType: function (store, typeName, primaryTypeClass) { var typeClass = store.modelFor(typeName); return typeClass.modelName === primaryTypeClass.modelName; }, /** 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) { var documentHash = { data: [], included: [] }; for (var prop in payload) { var modelName = this.modelNameFromPayloadKey(prop); if (!store.modelFactoryFor(modelName)) { (0, _emberDataPrivateDebug.warn)(this.warnMessageNoModelForKey(prop, modelName), false, { id: 'ds.serializer.model-for-key-missing' }); continue; } var type = store.modelFor(modelName); var typeSerializer = store.serializerFor(type.modelName); _ember.default.makeArray(payload[prop]).forEach(function (hash) { var _typeSerializer$normalize = typeSerializer.normalize(type, hash, prop); var data = _typeSerializer$normalize.data; var included = _typeSerializer$normalize.included; documentHash.data.push(data); if (included) { var _documentHash$included5; (_documentHash$included5 = documentHash.included).push.apply(_documentHash$included5, _toConsumableArray(included)); } }); } if ((0, _emberDataPrivateFeatures.default)('ds-pushpayload-return')) { return store.push(documentHash); } else { store.push(documentHash); } }, /** This method is used to convert each JSON root key in the payload into a modelName that it can use to look up the appropriate model for that part of the payload. For example, your server may send a model name that does not correspond with the name of the model in your app. Let's take a look at an example model, and an example payload: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ }); ``` ```javascript { "blog/post": { "id": "1 } } ``` Ember Data is going to normalize the payload's root key for the modelName. As a result, it will try to look up the "blog/post" model. Since we don't have a model called "blog/post" (or a file called app/models/blog/post.js in ember-cli), Ember Data will throw an error because it cannot find the "blog/post" model. Since we want to remove this namespace, we can define a serializer for the application that will remove "blog/" from the payload key whenver it's encountered by Ember Data: ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ modelNameFromPayloadKey: function(payloadKey) { if (payloadKey === 'blog/post') { return this._super(payloadKey.replace('blog/', '')); } else { return this._super(payloadKey); } } }); ``` After refreshing, Ember Data will appropriately look up the "post" model. By default the modelName for a model is its name in dasherized form. This means that a payload key like "blogPost" would be normalized to "blog-post" when Ember Data looks up the model. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadKey` for this purpose. @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ modelNameFromPayloadKey: function (key) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(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: ```app/models/comment.js import DS from 'ember-data'; export default 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. ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.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. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.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. ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = this._super(snapshot, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function (snapshot, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. The hash property should be modified by reference (possibly using something like _.extend) By default the REST Serializer sends the modelName of a model, which is a camelized version of the name. For example, your server may expect underscored root objects. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.modelName); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function (hash, typeClass, snapshot, options) { var normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName); hash[normalizedRootKey] = this.serialize(snapshot, options); }, /** You can use `payloadKeyFromModelName` to override the root key for an outgoing request. By default, the RESTSerializer returns a camelized version of the model's name. For a model called TacoParty, its `modelName` would be the string `taco-party`. The RESTSerializer will send it to the server with `tacoParty` as the root key in the JSON payload: ```js { "tacoParty": { "id": "1", "location": "Matthew Beale's House" } } ``` For example, your server may expect dasherized root objects: ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.dasherize(modelName); } }); ``` Given a `TacoParty` model, calling `save` on it would produce an outgoing request like: ```js { "taco-party": { "id": "1", "location": "Matthew Beale's House" } } ``` @method payloadKeyFromModelName @param {String} modelName @return {String} */ payloadKeyFromModelName: function (modelName) { return camelize(modelName); }, /** You can use this method to customize how polymorphic objects are serialized. By default the REST Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: function (snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); var typeKey = this.keyForPolymorphicType(key, relationship.type, 'serialize'); // old way of getting the key for the polymorphic type key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; key = key + "Type"; // The old way of serializing the type of a polymorphic record used // `keyForAttribute`, which is not correct. The next code checks if the old // way is used and if it differs from the new way of using // `keyForPolymorphicType`. If this is the case, a deprecation warning is // logged and the old way is restored (so nothing breaks). if (key !== typeKey && this.keyForPolymorphicType === RESTSerializer.prototype.keyForPolymorphicType) { (0, _emberDataPrivateDebug.deprecate)("The key to serialize the type of a polymorphic record is created via keyForAttribute which has been deprecated. Use the keyForPolymorphicType hook instead.", false, { id: 'ds.rest-serializer.deprecated-key-for-polymorphic-type', until: '3.0.0' }); typeKey = key; } if (_ember.default.isNone(belongsTo)) { json[typeKey] = null; } else { if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { json[typeKey] = this.payloadTypeFromModelName(belongsTo.modelName); } else { json[typeKey] = camelize(belongsTo.modelName); } } }, /** You can use this method to customize how a polymorphic relationship should be extracted. @method extractPolymorphicRelationship @param {Object} relationshipType @param {Object} relationshipHash @param {Object} relationshipOptions @return {Object} */ extractPolymorphicRelationship: function (relationshipType, relationshipHash, relationshipOptions) { var key = relationshipOptions.key; var resourceHash = relationshipOptions.resourceHash; var relationshipMeta = relationshipOptions.relationshipMeta; // A polymorphic belongsTo relationship can be present in the payload // either in the form where the `id` and the `type` are given: // // { // message: { id: 1, type: 'post' } // } // // or by the `id` and a `<relationship>Type` attribute: // // { // message: 1, // messageType: 'post' // } // // The next code checks if the latter case is present and returns the // corresponding JSON-API representation. The former case is handled within // the base class JSONSerializer. var isPolymorphic = relationshipMeta.options.polymorphic; var typeProperty = this.keyForPolymorphicType(key, relationshipType, 'deserialize'); if (isPolymorphic && resourceHash[typeProperty] !== undefined && typeof relationshipHash !== 'object') { if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { var payloadType = resourceHash[typeProperty]; var type = this.modelNameFromPayloadType(payloadType); var deprecatedTypeLookup = this.modelNameFromPayloadKey(payloadType); if (payloadType !== deprecatedTypeLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) { (0, _emberDataPrivateDebug.deprecate)("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.rest-serializer.deprecated-model-name-for-polymorphic-type', until: '3.0.0' }); type = deprecatedTypeLookup; } return { id: relationshipHash, type: type }; } else { var type = this.modelNameFromPayloadKey(resourceHash[typeProperty]); return { id: relationshipHash, type: type }; } } return this._super.apply(this, arguments); } }); if ((0, _emberDataPrivateFeatures.default)("ds-payload-type-hooks")) { RESTSerializer.reopen({ /** `modelNameFromPayloadType` can be used to change the mapping for a DS model name, taken from the value in the payload. Say your API namespaces the type of a model and returns the following payload for the `post` model, which has a polymorphic `user` relationship: ```javascript // GET /api/posts/1 { "post": { "id": 1, "user": 1, "userType: "api::v1::administrator" } } ``` By overwriting `modelNameFromPayloadType` you can specify that the `administrator` model should be used: ```app/serializers/application.js import DS from "ember-data"; export default DS.RESTSerializer.extend({ modelNameFromPayloadType(payloadType) { return payloadType.replace('api::v1::', ''); } }); ``` By default the modelName for a model is its name in dasherized form. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadType` for this purpose. Also take a look at [payloadTypeFromModelName](#method_payloadTypeFromModelName) to customize how the type of a record should be serialized. @method modelNameFromPayloadType @public @param {String} payloadType type from payload @return {String} modelName */ modelNameFromPayloadType: function (payloadType) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(payloadType)); }, /** `payloadTypeFromModelName` can be used to change the mapping for the type in the payload, taken from the model name. Say your API namespaces the type of a model and expects the following payload when you update the `post` model, which has a polymorphic `user` relationship: ```javascript // POST /api/posts/1 { "post": { "id": 1, "user": 1, "userType": "api::v1::administrator" } } ``` By overwriting `payloadTypeFromModelName` you can specify that the namespaces model name for the `administrator` should be used: ```app/serializers/application.js import DS from "ember-data"; export default DS.RESTSerializer.extend({ payloadTypeFromModelName(modelName) { return "api::v1::" + modelName; } }); ``` By default the payload type is the camelized model name. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `payloadTypeFromModelName` for this purpose. Also take a look at [modelNameFromPayloadType](#method_modelNameFromPayloadType) to customize how the model name from should be mapped from the payload. @method payloadTypeFromModelName @public @param {String} modelname modelName from the record @return {String} payloadType */ payloadTypeFromModelName: function (modelName) { return camelize(modelName); }, _hasCustomModelNameFromPayloadKey: function () { return this.modelNameFromPayloadKey !== RESTSerializer.prototype.modelNameFromPayloadKey; }, _hasCustomModelNameFromPayloadType: function () { return this.modelNameFromPayloadType !== RESTSerializer.prototype.modelNameFromPayloadType; }, _hasCustomPayloadTypeFromModelName: function () { return this.payloadTypeFromModelName !== RESTSerializer.prototype.payloadTypeFromModelName; }, _hasCustomPayloadKeyFromModelName: function () { return this.payloadKeyFromModelName !== RESTSerializer.prototype.payloadKeyFromModelName; } }); } (0, _emberDataPrivateDebug.runInDebug)(function () { RESTSerializer.reopen({ warnMessageNoModelForKey: function (prop, typeKey) { return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.modelNameFromPayloadKey("' + prop + '"))'; } }); }); exports.default = RESTSerializer; }); /** @module ember-data */ define('ember-data/setup-container', ['exports', 'ember-data/-private/initializers/store', 'ember-data/-private/initializers/transforms', 'ember-data/-private/initializers/store-injections', 'ember-data/-private/initializers/data-adapter'], function (exports, _emberDataPrivateInitializersStore, _emberDataPrivateInitializersTransforms, _emberDataPrivateInitializersStoreInjections, _emberDataPrivateInitializersDataAdapter) { exports.default = setupContainer; function setupContainer(application) { (0, _emberDataPrivateInitializersDataAdapter.default)(application); (0, _emberDataPrivateInitializersTransforms.default)(application); (0, _emberDataPrivateInitializersStoreInjections.default)(application); (0, _emberDataPrivateInitializersStore.default)(application); } }); define("ember-data/store", ["exports", "ember-data/-private/system/store"], function (exports, _emberDataPrivateSystemStore) { exports.default = _emberDataPrivateSystemStore.default; }); define('ember-data/transform', ['exports', 'ember'], function (exports, _ember) { /** 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 ```app/transforms/temperature.js import DS from 'ember-data'; // Converts centigrade in the JSON to fahrenheit in the app export default DS.Transform.extend({ deserialize: function(serialized, options) { return (serialized * 1.8) + 32; }, serialize: function(deserialized, options) { return (deserialized - 32) / 1.8; } }); ``` The options passed into the `DS.attr` function when the attribute is declared on the model is also available in the transform. ```app/models/post.js export default DS.Model.extend({ title: DS.attr('string'), markdown: DS.attr('markdown', { markdown: { gfm: false, sanitize: true } }) }); ``` ```app/transforms/markdown.js export default DS.Transform.extend({ serialize: function (deserialized, options) { return deserialized.raw; }, deserialize: function (serialized, options) { var markdownOptions = options.markdown || {}; return marked(serialized, markdownOptions); } }); ``` Usage ```app/models/requirement.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr('string'), temperature: DS.attr('temperature') }); ``` @class Transform @namespace DS */ exports.default = _ember.default.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized, options) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @param options hash of options passed to `DS.attr` @return The serialized value */ serialize: null, /** 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, options) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @param options hash of options passed to `DS.attr` @return The deserialized value */ deserialize: null }); }); define("ember-data/version", ["exports"], function (exports) { exports.default = "2.9.0-beta.4"; }); define("ember-inflector", ["exports", "ember", "ember-inflector/lib/system", "ember-inflector/lib/ext/string"], function (exports, _ember, _emberInflectorLibSystem, _emberInflectorLibExtString) { _emberInflectorLibSystem.Inflector.defaultRules = _emberInflectorLibSystem.defaultRules; _ember.default.Inflector = _emberInflectorLibSystem.Inflector; _ember.default.String.pluralize = _emberInflectorLibSystem.pluralize; _ember.default.String.singularize = _emberInflectorLibSystem.singularize; exports.default = _emberInflectorLibSystem.Inflector; exports.pluralize = _emberInflectorLibSystem.pluralize; exports.singularize = _emberInflectorLibSystem.singularize; exports.defaultRules = _emberInflectorLibSystem.defaultRules; if (typeof define !== 'undefined' && define.amd) { define('ember-inflector', ['exports'], function (__exports__) { __exports__['default'] = _emberInflectorLibSystem.Inflector; return _emberInflectorLibSystem.Inflector; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = _emberInflectorLibSystem.Inflector; } }); /* global define, module */ define('ember-inflector/lib/ext/string', ['exports', 'ember', 'ember-inflector/lib/system/string'], function (exports, _ember, _emberInflectorLibSystemString) { if (_ember.default.EXTEND_PROTOTYPES === true || _ember.default.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function () { return (0, _emberInflectorLibSystemString.pluralize)(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function () { return (0, _emberInflectorLibSystemString.singularize)(this); }; } }); define('ember-inflector/lib/helpers/pluralize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _emberInflectorLibUtilsMakeHelper) { /** * * If you have Ember Inflector (such as if Ember Data is present), * pluralize a word. For example, turn "ox" into "oxen". * * Example: * * {{pluralize count myProperty}} * {{pluralize 1 "oxen"}} * {{pluralize myProperty}} * {{pluralize "ox"}} * * @for Ember.HTMLBars.helpers * @method pluralize * @param {Number|Property} [count] count of objects * @param {String|Property} word word to pluralize */ exports.default = (0, _emberInflectorLibUtilsMakeHelper.default)(function (params) { var count = undefined, word = undefined; if (params.length === 1) { word = params[0]; return (0, _emberInflector.pluralize)(word); } else { count = params[0]; word = params[1]; if (parseFloat(count) !== 1) { word = (0, _emberInflector.pluralize)(word); } return count + " " + word; } }); }); define('ember-inflector/lib/helpers/singularize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _emberInflectorLibUtilsMakeHelper) { /** * * If you have Ember Inflector (such as if Ember Data is present), * singularize a word. For example, turn "oxen" into "ox". * * Example: * * {{singularize myProperty}} * {{singularize "oxen"}} * * @for Ember.HTMLBars.helpers * @method singularize * @param {String|Property} word word to singularize */ exports.default = (0, _emberInflectorLibUtilsMakeHelper.default)(function (params) { return (0, _emberInflector.singularize)(params[0]); }); }); define("ember-inflector/lib/system", ["exports", "ember-inflector/lib/system/inflector", "ember-inflector/lib/system/string", "ember-inflector/lib/system/inflections"], function (exports, _emberInflectorLibSystemInflector, _emberInflectorLibSystemString, _emberInflectorLibSystemInflections) { _emberInflectorLibSystemInflector.default.inflector = new _emberInflectorLibSystemInflector.default(_emberInflectorLibSystemInflections.default); exports.Inflector = _emberInflectorLibSystemInflector.default; exports.singularize = _emberInflectorLibSystemString.singularize; exports.pluralize = _emberInflectorLibSystemString.pluralize; exports.defaultRules = _emberInflectorLibSystemInflections.default; }); define('ember-inflector/lib/system/inflections', ['exports'], function (exports) { exports.default = { plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status|bonus)$/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|bonus)(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'] }; }); define('ember-inflector/lib/system/inflector', ['exports', 'ember'], function (exports, _ember) { var capitalize = _ember.default.String.capitalize; var BLANK_REGEX = /^\s*$/; var LAST_WORD_DASHED_REGEX = /([\w/-]+[_/\s-])([a-z\d]+$)/; var LAST_WORD_CAMELIZED_REGEX = /([\w/\s-]+)([A-Z][a-z\d]*$)/; var CAMELIZED_REGEX = /[A-Z][a-z\d]*$/; 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]; //pluralizing rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregular[pair[1].toLowerCase()] = pair[1]; //singularizing rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; rules.irregularInverse[pair[0].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 || makeDictionary(); ruleSet.irregularPairs = ruleSet.irregularPairs || makeDictionary(); var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: makeDictionary(), irregularInverse: makeDictionary(), uncountable: makeDictionary() }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); this.enableCache(); } if (!Object.create && !Object.create(null).hasOwnProperty) { throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); } function makeDictionary() { var cache = Object.create(null); cache['_dict'] = null; delete cache['_dict']; return cache; } Inflector.prototype = { /** @public As inflections can be costly, and commonly the same subset of words are repeatedly inflected an optional cache is provided. @method enableCache */ enableCache: function () { this.purgeCache(); this.singularize = function (word) { this._cacheUsed = true; return this._sCache[word] || (this._sCache[word] = this._singularize(word)); }; this.pluralize = function (word) { this._cacheUsed = true; return this._pCache[word] || (this._pCache[word] = this._pluralize(word)); }; }, /** @public @method purgedCache */ purgeCache: function () { this._cacheUsed = false; this._sCache = makeDictionary(); this._pCache = makeDictionary(); }, /** @public disable caching @method disableCache; */ disableCache: function () { this._sCache = null; this._pCache = null; this.singularize = function (word) { return this._singularize(word); }; this.pluralize = function (word) { return this._pluralize(word); }; }, /** @method plural @param {RegExp} regex @param {String} string */ plural: function (regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function (regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function (string) { if (this._cacheUsed) { this.purgeCache(); } loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { if (this._cacheUsed) { this.purgeCache(); } loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function (word) { return this._pluralize(word); }, _pluralize: function (word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function (word) { return this._singularize(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, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, rule, isUncountable; isBlank = !word || BLANK_REGEX.test(word); isCamelized = CAMELIZED_REGEX.test(word); firstPhrase = ""; if (isBlank) { return word; } lowercase = word.toLowerCase(); wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word); if (wordSplit) { firstPhrase = wordSplit[1]; lastWord = wordSplit[2].toLowerCase(); } isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord]; if (isUncountable) { return word; } for (rule in irregular) { if (lowercase.match(rule + "$")) { substitution = irregular[rule]; if (isCamelized && irregular[lastWord]) { substitution = capitalize(substitution); rule = capitalize(rule); } return word.replace(new RegExp(rule, 'i'), substitution); } } 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', ['exports', 'ember-inflector/lib/system/inflector'], function (exports, _emberInflectorLibSystemInflector) { function pluralize(word) { return _emberInflectorLibSystemInflector.default.inflector.pluralize(word); } function singularize(word) { return _emberInflectorLibSystemInflector.default.inflector.singularize(word); } exports.pluralize = pluralize; exports.singularize = singularize; }); define('ember-inflector/lib/utils/make-helper', ['exports', 'ember'], function (exports, _ember) { exports.default = makeHelper; function makeHelper(helperFunction) { if (_ember.default.Helper) { return _ember.default.Helper.helper(helperFunction); } if (_ember.default.HTMLBars) { return _ember.default.HTMLBars.makeBoundHelper(helperFunction); } return _ember.default.Handlebars.makeBoundHelper(helperFunction); } }); define('ember-load-initializers', ['exports', 'ember'], function (exports, _ember) { exports.default = function (app, prefix) { var regex = new RegExp('^' + prefix + '\/((?:instance-)?initializers)\/'); var getKeys = Object.keys || _ember.default.keys; getKeys(requirejs._eak_seen).map(function (moduleName) { return { moduleName: moduleName, matches: regex.exec(moduleName) }; }).filter(function (dep) { return dep.matches && dep.matches.length === 2; }).forEach(function (dep) { var moduleName = dep.moduleName; var module = require(moduleName, null, null, true); if (!module) { throw new Error(moduleName + ' must export an initializer.'); } var initializerType = _ember.default.String.camelize(dep.matches[1].substring(0, dep.matches[1].length - 1)); var initializer = module['default']; if (!initializer.name) { var initializerName = moduleName.match(/[^\/]+\/?$/)[0]; initializer.name = initializerName; } if (app[initializerType]) { app[initializerType](initializer); } }); }; }); define('ember', [], function() { return { default: Ember }; }); require("ember-data"); require("ember-load-initializers")["default"](Ember.Application, "ember-data"); ;(function() { var global = require('ember-data/-private/global').default; var DS = require('ember-data').default; Object.defineProperty(global, 'DS', { get: function() { return DS; } }); })(); })(); ;(function() { function processEmberDataShims() { var shims = { 'ember-data': { default: DS }, 'ember-data/model': { default: DS.Model }, 'ember-data/mixins/embedded-records': { default: DS.EmbeddedRecordsMixin }, 'ember-data/serializers/rest': { default: DS.RESTSerializer }, 'ember-data/serializers/active-model': { default: DS.ActiveModelSerializer }, 'ember-data/serializers/json': { default: DS.JSONSerializer }, 'ember-data/serializers/json-api': { default: DS.JSONAPISerializer }, 'ember-data/serializer': { default: DS.Serializer }, 'ember-data/adapters/json-api': { default: DS.JSONAPIAdapter }, 'ember-data/adapters/rest': { default: DS.RESTAdapter }, 'ember-data/adapter': { default: DS.Adapter }, 'ember-data/adapters/active-model': { default: DS.ActiveModelAdapter }, 'ember-data/store': { default: DS.Store }, 'ember-data/transform': { default: DS.Transform }, 'ember-data/attr': { default: DS.attr }, 'ember-data/relationships': { hasMany: DS.hasMany, belongsTo: DS.belongsTo } }; for (var moduleName in shims) { generateModule(moduleName, shims[moduleName]); } } function generateModule(name, values) { define(name, [], function() { 'use strict'; return values; }); } if (typeof define !== 'undefined' && define && define.petal) { processEmberDataShims(); } })();
ajax/libs/antd-mobile/1.0.0-alpha.15/antd-mobile.min.js
sreym/cdnjs
/*! * antd-mobile v1.0.0-alpha.15 * * Copyright 2015-present, Alipay, Inc. * All rights reserved. */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports["antd-mobile"]=t(require("react"),require("react-dom")):e["antd-mobile"]=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(i){if(n[i])return n[i].exports;var r=n[i]={exports:{},id:i,loaded:!1};return e[i].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var n=t.slice(1),i=e[t[0]];return function(e,t,r){i.apply(this,[e,t,r].concat(n))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,n){e.exports=n(125)},function(t,n){t.exports=e},function(e,t){"use strict";t.__esModule=!0,t["default"]=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var r=n(222),o=i(r),a=n(219),s=i(a),l=n(34),u=i(l);t["default"]=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+("undefined"==typeof t?"undefined":(0,u["default"])(t)));e.prototype=(0,s["default"])(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(o["default"]?(0,o["default"])(e,t):e.__proto__=t)}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var r=n(34),o=i(r);t["default"]=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==("undefined"==typeof t?"undefined":(0,o["default"])(t))&&"function"!=typeof t?e:t}},function(e,t,n){var i,r;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var i=arguments[t];if(i){var r=typeof i;if("string"===r||"number"===r)e.push(i);else if(Array.isArray(i))e.push(n.apply(null,i));else if("object"===r)for(var a in i)o.call(i,a)&&i[a]&&e.push(a)}}return e.join(" ")}var o={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(i=[],r=function(){return n}.apply(t,i),!(void 0!==r&&(e.exports=r)))}()},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var r=n(220),o=i(r);t["default"]=function(e,t,n){return t in e?(0,o["default"])(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var r=n(218),o=i(r);t["default"]=o["default"]||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e}},function(e,t,n){"use strict";n(324),n(313)},function(e,n){e.exports=t},function(e,t){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function i(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var i=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==i.join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(o){return!1}}var r=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;e.exports=i()?Object.assign:function(e,t){for(var i,a,s=n(e),l=1;l<arguments.length;l++){i=Object(arguments[l]);for(var u in i)r.call(i,u)&&(s[u]=i[u]);if(Object.getOwnPropertySymbols){a=Object.getOwnPropertySymbols(i);for(var c=0;c<a.length;c++)o.call(i,a[c])&&(s[a[c]]=i[a[c]])}}return s}},function(e,t){var n=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(e,t,n){var i=n(63)("wks"),r=n(43),o=n(18).Symbol,a="function"==typeof o,s=e.exports=function(e){return i[e]||(i[e]=a&&o[e]||(a?o:r)("Symbol."+e))};s.store=i},function(e,t,n){"use strict";function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),a=r(o),s=n(2),l=r(s),u=n(4),c=r(u),d=n(3),f=r(d),p=n(1),h=i(p),m=n(5),y=r(m),v=function(e){function t(){(0,l["default"])(this,t);var i=(0,c["default"])(this,e.apply(this,arguments));return i.renderSvg=function(){var e=void 0;try{e=n(121)("./"+i.props.type+".svg")}finally{return e}},i}return(0,f["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.type,i=t.className,r=t.style,o=t.size,s=void 0===o?"md":o,l=this.renderSvg();l=l?"#"+n:n;var u=(0,y["default"])((e={"am-icon":!0},(0,a["default"])(e,"am-icon-"+n,!0),(0,a["default"])(e,"am-icon-"+s,!0),(0,a["default"])(e,i,!!i),e));return h.createElement("svg",{className:u,style:r},h.createElement("use",{xlinkHref:l}))},t}(h.Component);t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var r=n(217),o=i(r),a=n(216),s=i(a);t["default"]=function(){function e(e,t){var n=[],i=!0,r=!1,o=void 0;try{for(var a,l=(0,s["default"])(e);!(i=(a=l.next()).done)&&(n.push(a.value),!t||n.length!==t);i=!0);}catch(u){r=!0,o=u}finally{try{!i&&l["return"]&&l["return"]()}finally{if(r)throw o}}return n}return function(t,n){if(Array.isArray(t))return t;if((0,o["default"])(Object(t)))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()},function(e,t){"use strict";function n(e,t){var n={},i={};return Object.keys(e).forEach(function(r){t.indexOf(r)!==-1?n[r]=e[r]:i[r]=e[r]}),[n,i]}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";n(291)},function(e,t,n){var i=n(18),r=n(11),o=n(55),a=n(28),s="prototype",l=function(e,t,n){var u,c,d,f=e&l.F,p=e&l.G,h=e&l.S,m=e&l.P,y=e&l.B,v=e&l.W,g=p?r:r[t]||(r[t]={}),b=g[s],M=p?i:h?i[t]:(i[t]||{})[s];p&&(n=t);for(u in n)c=!f&&M&&void 0!==M[u],c&&u in g||(d=c?M[u]:n[u],g[u]=p&&"function"!=typeof M[u]?n[u]:y&&c?o(d,i):v&&M[u]==d?function(e){var t=function(t,n,i){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,i)}return e.apply(this,arguments)};return t[s]=e[s],t}(d):m&&"function"==typeof d?o(Function.call,d):d,m&&((g.virtual||(g.virtual={}))[u]=d,e&l.R&&b&&!b[u]&&a(b,u,d)))};l.F=1,l.G=2,l.S=4,l.P=8,l.B=16,l.W=32,l.U=64,l.R=128,e.exports=l},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var i=n(21),r=n(93),o=n(65),a=Object.defineProperty;t.f=n(22)?Object.defineProperty:function(e,t,n){if(i(e),t=o(t,!0),i(n),r)try{return a(e,t,n)}catch(s){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},[451,295],function(e,t,n){var i=n(35);e.exports=function(e){if(!i(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n){e.exports=!n(27)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var i=n(94),r=n(56);e.exports=function(e){return i(r(e))}},function(e,t){"use strict";function n(e){var t={};return Object.keys(e).forEach(function(n){0===n.indexOf("data-")&&(t[n]=e[n])}),t}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(158),m=i(h),y=n(5),v=i(y),g=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.children,r=t.className,a=t.style,s=t.renderHeader,l=t.renderFooter,u=(0,v["default"])((e={},(0,o["default"])(e,n,!0),(0,o["default"])(e,r,r),e));return p["default"].createElement("div",{className:u,style:a},s?p["default"].createElement("div",{className:n+"-header"},s()):null,i?p["default"].createElement("div",{className:n+"-body"},i):null,l?p["default"].createElement("div",{className:n+"-footer"},l()):null)},t}(p["default"].Component);t["default"]=g,g.Item=m["default"],g.defaultProps={prefixCls:"am-list"},e.exports=t["default"]},function(e,t){e.exports=function(e){try{return!!e()}catch(t){return!0}}},function(e,t,n){var i=n(19),r=n(36);e.exports=n(22)?function(e,t,n){return i.f(e,t,r(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t){e.exports={}},function(e,t,n){var i=n(98),r=n(57);e.exports=Object.keys||function(e){return i(e,r)}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=l["default"].createClass({displayName:"TouchableFeedbackComponent",statics:{myName:t||"TouchableFeedbackComponent"},getDefaultProps:function(){return{activeStyle:{}}},getInitialState:function(){return{touchFeedback:!1}},onTouchStart:function(e){this.props.onTouchStart&&this.props.onTouchStart(e),this.setTouchFeedbackState(!0)},onTouchEnd:function(e){this.props.onTouchEnd&&this.props.onTouchEnd(e),this.setTouchFeedbackState(!1)},onTouchCancel:function(e){this.props.onTouchCancel&&this.props.onTouchCancel(e),this.setTouchFeedbackState(!1)},onMouseDown:function(e){this.props.onTouchStart&&this.props.onTouchStart(e),this.setTouchFeedbackState(!0)},onMouseUp:function(e){this.props.onTouchEnd&&this.props.onTouchEnd(e),this.setTouchFeedbackState(!1)},setTouchFeedbackState:function(e){this.setState({touchFeedback:e})},render:function(){var t={};return this.props.activeStyle&&(t=u?{onTouchStart:this.onTouchStart,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchCancel}:{onMouseDown:this.onMouseDown,onMouseUp:this.state.touchFeedback?this.onMouseUp:void 0,onMouseLeave:this.state.touchFeedback?this.onMouseUp:void 0}),l["default"].createElement(e,(0,a["default"])({},this.props,{touchFeedback:this.state.touchFeedback},t))}});return n}Object.defineProperty(t,"__esModule",{value:!0});var o=n(7),a=i(o);t["default"]=r;var s=n(1),l=i(s),u="undefined"!=typeof window&&"ontouchstart"in window;e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(147),o=i(r),a=n(148),s=i(a);o["default"].Item=s["default"],t["default"]=o["default"],e.exports=t["default"]},[451,289],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var r=n(224),o=i(r),a=n(223),s=i(a),l="function"==typeof s["default"]&&"symbol"==typeof o["default"]?function(e){return typeof e}:function(e){return e&&"function"==typeof s["default"]&&e.constructor===s["default"]&&e!==s["default"].prototype?"symbol":typeof e};t["default"]="function"==typeof s["default"]&&"symbol"===l(o["default"])?function(e){return"undefined"==typeof e?"undefined":l(e)}:function(e){return e&&"function"==typeof s["default"]&&e.constructor===s["default"]&&e!==s["default"].prototype?"symbol":"undefined"==typeof e?"undefined":l(e)}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){"use strict";function i(e,t){return e+t}function r(e,t,n){var i=n;{if("object"!==("undefined"==typeof t?"undefined":w(t)))return"undefined"!=typeof i?("number"==typeof i&&(i+="px"),void(e.style[t]=i)):E(e,t);for(var o in t)t.hasOwnProperty(o)&&r(e,o,t[o])}}function o(e){var t=void 0,n=void 0,i=void 0,r=e.ownerDocument,o=r.body,a=r&&r.documentElement;return t=e.getBoundingClientRect(),n=t.left,i=t.top,n-=a.clientLeft||o.clientLeft||0,i-=a.clientTop||o.clientTop||0,{left:n,top:i}}function a(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],i="scroll"+(t?"Top":"Left");if("number"!=typeof n){var r=e.document;n=r.documentElement[i],"number"!=typeof n&&(n=r.body[i])}return n}function s(e){return a(e)}function l(e){return a(e,!0)}function u(e){var t=o(e),n=e.ownerDocument,i=n.defaultView||n.parentWindow;return t.left+=s(i),t.top+=l(i),t}function c(e,t,n){var i=n,r="",o=e.ownerDocument;return i=i||o.defaultView.getComputedStyle(e,null),i&&(r=i.getPropertyValue(t)||i[t]),r}function d(e,t){var n=e[I]&&e[I][t];if(P.test(n)&&!D.test(t)){var i=e.style,r=i[j],o=e[L][j];e[L][j]=e[I][j],i[j]="fontSize"===t?"1em":n||0,n=i.pixelLeft+k,i[j]=r,e[L][j]=o}return""===n?"auto":n}function f(e,t){return"left"===e?t.useCssRight?"right":e:t.useCssBottom?"bottom":e}function p(e){return"left"===e?"right":"right"===e?"left":"top"===e?"bottom":"bottom"===e?"top":void 0}function h(e,t,n){"static"===r(e,"position")&&(e.style.position="relative");var o=-999,a=-999,s=f("left",n),l=f("top",n),c=p(s),d=p(l);"left"!==s&&(o=999),"top"!==l&&(a=999);var h="",m=u(e);("left"in t||"top"in t)&&(h=(0,S.getTransitionProperty)(e)||"",(0,S.setTransitionProperty)(e,"none")),"left"in t&&(e.style[c]="",e.style[s]=o+"px"),"top"in t&&(e.style[d]="",e.style[l]=a+"px");var y=u(e),v={};for(var g in t)if(t.hasOwnProperty(g)){var b=f(g,n),M="left"===g?o:a,T=m[g]-y[g];b===g?v[b]=M+T:v[b]=M-T}r(e,v),i(e.offsetTop,e.offsetLeft),("left"in t||"top"in t)&&(0,S.setTransitionProperty)(e,h);var x={};for(var C in t)if(t.hasOwnProperty(C)){var _=f(C,n),w=t[C]-m[C];C===_?x[_]=v[_]+w:x[_]=v[_]-w}r(e,x)}function m(e,t){var n=u(e),i=(0,S.getTransformXY)(e),r={x:i.x,y:i.y};"left"in t&&(r.x=i.x+t.left-n.left),"top"in t&&(r.y=i.y+t.top-n.top),(0,S.setTransformXY)(e,r)}function y(e,t,n){n.useCssRight||n.useCssBottom?h(e,t,n):n.useCssTransform&&(0,S.getTransformName)()in document.body.style?m(e,t,n):h(e,t,n)}function v(e,t){for(var n=0;n<e.length;n++)t(e[n])}function g(e){return"border-box"===E(e,"boxSizing")}function b(e,t,n){var i={},r=e.style,o=void 0;for(o in t)t.hasOwnProperty(o)&&(i[o]=r[o],r[o]=t[o]);n.call(e);for(o in t)t.hasOwnProperty(o)&&(r[o]=i[o])}function M(e,t,n){var i=0,r=void 0,o=void 0,a=void 0;for(o=0;o<t.length;o++)if(r=t[o])for(a=0;a<n.length;a++){var s=void 0;s="border"===r?""+r+n[a]+"Width":r+n[a],i+=parseFloat(E(e,s))||0}return i}function T(e){return null!==e&&void 0!==e&&e==e.window}function x(e,t,n){var i=n;if(T(e))return"width"===t?Y.viewportWidth(e):Y.viewportHeight(e);if(9===e.nodeType)return"width"===t?Y.docWidth(e):Y.docHeight(e);var r="width"===t?["Left","Right"]:["Top","Bottom"],o="width"===t?e.offsetWidth:e.offsetHeight,a=E(e),s=g(e,a),l=0;(null===o||void 0===o||o<=0)&&(o=void 0,l=E(e,t),(null===l||void 0===l||Number(l)<0)&&(l=e.style[t]||0),l=parseFloat(l)||0),void 0===i&&(i=s?R:A);var u=void 0!==o||s,c=o||l;return i===A?u?c-M(e,["border","padding"],r,a):l:u?i===R?c:c+(i===z?-M(e,["border"],r,a):M(e,["margin"],r,a)):l+M(e,O.slice(i),r,a)}function C(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var i=void 0,r=t[0];return 0!==r.offsetWidth?i=x.apply(void 0,t):b(r,H,function(){i=x.apply(void 0,t)}),i}function _(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}Object.defineProperty(t,"__esModule",{value:!0});var w="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},S=n(278),N=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,E=void 0,P=new RegExp("^("+N+")(?!px)[a-z%]+$","i"),D=/^(top|right|bottom|left)$/,I="currentStyle",L="runtimeStyle",j="left",k="px";"undefined"!=typeof window&&(E=window.getComputedStyle?c:d);var O=["margin","border","padding"],A=-1,z=2,R=1,W=0,Y={};v(["Width","Height"],function(e){Y["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],Y["viewport"+e](n))},Y["viewport"+e]=function(t){var n="client"+e,i=t.document,r=i.body,o=i.documentElement,a=o[n];return"CSS1Compat"===i.compatMode&&a||r&&r[n]||a}});var H={position:"absolute",visibility:"hidden",display:"block"};v(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);Y["outer"+t]=function(t,n){return t&&C(t,e,n?W:R)};var n="width"===e?["Left","Right"]:["Top","Bottom"];Y[e]=function(t,i){var o=i;{if(void 0===o)return t&&C(t,e,A);if(t){var a=E(t),s=g(t);return s&&(o+=M(t,["padding","border"],n,a)),r(t,e,o)}}}});var B={getWindow:function(e){if(e&&e.document&&e.setTimeout)return e;var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},offset:function(e,t,n){return"undefined"==typeof t?u(e):void y(e,t,n||{})},isWindow:T,each:v,css:r,clone:function(e){var t=void 0,n={};for(t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);var i=e.overflow;if(i)for(t in e)e.hasOwnProperty(t)&&(n.overflow[t]=e.overflow[t]);return n},mix:_,getWindowScrollLeft:function(e){return s(e)},getWindowScrollTop:function(e){return l(e)},merge:function(){for(var e={},t=arguments.length,n=Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var r=0;r<n.length;r++)B.mix(e,n[r]);return e},viewportWidth:0,viewportHeight:0};_(B,Y),t["default"]=B,e.exports=t["default"]},function(e,t,n){"use strict";var i=n(10);e.exports=function(e,t){for(var n=i({},e),r=0;r<t.length;r++){var o=t[r];delete n[o]}return n}},function(e,t,n){"use strict";var i=n(335);e.exports=function(e,t,n,r){var o=n?n.call(r,e,t):void 0;if(void 0!==o)return!!o;if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var a=i(e),s=i(t),l=a.length;if(l!==s.length)return!1;r=r||null;for(var u=Object.prototype.hasOwnProperty.bind(t),c=0;c<l;c++){var d=a[c];if(!u(d))return!1;var f=e[d],p=t[d],h=n?n.call(r,f,p,d):void 0;if(h===!1||void 0===h&&f!==p)return!1}return!0}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){function i(t){var i=new a["default"](t);n.call(e,i)}return e.addEventListener?(e.addEventListener(t,i,!1),{remove:function(){e.removeEventListener(t,i,!1)}}):e.attachEvent?(e.attachEvent("on"+t,i),{remove:function(){e.detachEvent("on"+t,i)}}):void 0}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var o=n(123),a=i(o);e.exports=t["default"]},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var i=n(56);e.exports=function(e){return Object(i(e))}},function(e,t){var n=0,i=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+i).toString(36))}},function(e,t,n){"use strict";var i=n(256)(!0);n(95)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=i(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){"use strict";e.exports=n(345)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(354),s=i(a),l=n(357),u=i(l),c=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},d=o["default"].createClass({displayName:"DialogWrap",mixins:[(0,u["default"])({isVisible:function(e){return e.props.visible},autoDestroy:!1,getComponent:function(e,t){return o["default"].createElement(s["default"],c({},e.props,t,{key:"dialog"}))}})],getDefaultProps:function(){return{visible:!1}},shouldComponentUpdate:function(e){var t=e.visible;return!(!this.props.visible&&!t)},componentWillUnmount:function(){this.props.visible?this.renderComponent({afterClose:this.removeContainer,onClose:function(){},visible:!1}):this.removeContainer()},getElement:function(e){return this._component.getElement(e)},render:function(){return null}});t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){return"string"==typeof e}function o(e){return r(e.type)&&I(e.props.children)?b["default"].cloneElement(e,{},e.props.children.split("").join(" ")):r(e)?(I(e)&&(e=e.split("").join(" ")),b["default"].createElement("span",null,e)):e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),s=i(a),l=n(6),u=i(l),c=n(14),d=i(c),f=n(2),p=i(f),h=n(4),m=i(h),y=n(3),v=i(y),g=n(1),b=i(g),M=n(5),T=i(M),x=n(10),C=i(x),_=n(13),w=i(_),S=n(15),N=i(S),E=n(31),P=i(E),D=/^[\u4e00-\u9fa5]{2}$/,I=D.test.bind(D),L=function(e){function t(){return(0,p["default"])(this,t),(0,m["default"])(this,e.apply(this,arguments))}return(0,v["default"])(t,e),t.prototype.render=function(){var e,t=(0,N["default"])(this.props,["children","className","prefixCls","type","size","inline","across","disabled","htmlType","icon","loading","touchFeedback","activeStyle"]),n=(0,d["default"])(t,2),i=n[0],r=i.children,a=i.className,l=i.prefixCls,c=i.type,f=i.size,p=i.inline,h=i.across,m=i.disabled,y=i.htmlType,v=i.icon,g=i.loading,M=i.touchFeedback,x=i.activeStyle,_=n[1],S=(e={},(0,u["default"])(e,a,a),(0,u["default"])(e,l,!0),(0,u["default"])(e,l+"-primary","primary"===c),(0,u["default"])(e,l+"-ghost","ghost"===c),(0,u["default"])(e,l+"-warning","warning"===c),(0,u["default"])(e,l+"-small","small"===f),(0,u["default"])(e,l+"-inline",p),(0,u["default"])(e,l+"-across",h),(0,u["default"])(e,l+"-disabled",m),(0,u["default"])(e,l+"-loading",g),e),E=(0,C["default"])({},this.props.style);M&&(E=(0,C["default"])(E,x),S[l+"-active"]=!0);var P=g?"loading":v,D=b["default"].Children.map(r,o);return P&&(S[l+"-icon"]=!0),b["default"].createElement("button",(0,s["default"])({},_,{style:E,type:y||"button",className:(0,T["default"])(S),disabled:m}),P?b["default"].createElement(w["default"],{type:P}):null,D)},t}(b["default"].Component);L.defaultProps={prefixCls:"am-button",size:"large",inline:!1,across:!1,disabled:!1,loading:!1},t["default"]=(0,P["default"])(L),e.exports=t["default"]},[452,284],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(2),o=i(r),a=n(4),s=i(a),l=n(3),u=i(l),c=n(1),d=i(c),f=n(108),p=i(f),h=function(e){function t(){return(0,o["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){return d["default"].createElement(p["default"],this.props)},t}(d["default"].Component);t["default"]=h,h.defaultProps={prefixCls:"am-checkbox"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(6),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(46),v=i(y),g=n(5),b=i(g),M=n(10),T=i(M),x=n(162),C=i(x),_=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.isInModal=function(e){var t=this.props.prefixCls,n=function(e){for(;e.parentNode&&e.parentNode!==document.body;){if(e.classList.contains(t))return e;e=e.parentNode}}(e.target);return n||e.preventDefault(),!0},t.prototype.render=function(){var e,t=this,n=this.props,i=n.prefixCls,r=n.className,a=n.transparent,l=n.animated,u=n.transitionName,c=n.maskTransitionName,d=n.style,f=n.footer,p=void 0===f?[]:f,h=(0,b["default"])((e={},(0,s["default"])(e,r,!!r),(0,s["default"])(e,i+"-transparent",a),e)),y=u||(l?a?"am-fade":"am-slide-up":null),g=c||(l?a?"am-fade":"am-slide-up":null),M=i+"-button-group-"+(2===p.length?"h":"v"),x=p.length?[m["default"].createElement("div",{key:"footer",className:M},p.map(function(e,t){return m["default"].createElement(C["default"],{prefixCls:i,button:e,key:t})}))]:null,_=a?(0,T["default"])({width:"5.4rem",height:"auto"},d):(0,T["default"])({width:"100%",height:"100%"},d),w=(0,T["default"])({},this.props);["prefixCls","className","transparent","animated","transitionName","maskTransitionName","style","footer","touchFeedback","wrapProps"].forEach(function(e){w.hasOwnProperty(e)&&delete w[e]});var S=new RegExp("\\biPhone\\b|\\biPod\\b","i").test(window.navigator.userAgent),N=S?{onTouchStart:function(e){return t.isInModal(e)}}:{};return m["default"].createElement(v["default"],(0,o["default"])({prefixCls:i,className:h,transitionName:y,maskTransitionName:g,style:_,footer:x,wrapProps:N},w))},t}(m["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-modal",transparent:!1,animated:!0,style:{},onShow:function(){},footer:[]},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(108),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){return p["default"].createElement(m["default"],(0,o["default"])({},this.props,{type:"radio"}))},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-radio"},e.exports=t["default"]},function(e,t){"use strict";t.__esModule=!0,t["default"]=function(e,t){var n={};for(var i in e)t.indexOf(i)>=0||Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var r=n(215),o=i(r);t["default"]=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return(0,o["default"])(e)}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var i=n(236);e.exports=function(e,t,n){if(i(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,i){return e.call(t,n,i)};case 3:return function(n,i,r){return e.call(t,n,i,r)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){e.exports=!0},function(e,t,n){var i=n(21),r=n(251),o=n(57),a=n(62)("IE_PROTO"),s=function(){},l="prototype",u=function(){var e,t=n(92)("iframe"),i=o.length,r="<",a=">";for(t.style.display="none",n(241).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(r+"script"+a+"document.F=Object"+r+"/script"+a),e.close(),u=e.F;i--;)delete u[l][o[i]];return u()};e.exports=Object.create||function(e,t){var n;return null!==e?(s[l]=i(e),n=new s,s[l]=null,n[a]=e):n=u(),void 0===t?n:r(n,t)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var i=n(19).f,r=n(23),o=n(12)("toStringTag");e.exports=function(e,t,n){e&&!r(e=n?e:e.prototype,o)&&i(e,o,{configurable:!0,value:t})}},function(e,t,n){var i=n(63)("keys"),r=n(43);e.exports=function(e){return i[e]||(i[e]=r(e))}},function(e,t,n){var i=n(18),r="__core-js_shared__",o=i[r]||(i[r]={});e.exports=function(e){return o[e]||(o[e]={})}},function(e,t){var n=Math.ceil,i=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?i:n)(e)}},function(e,t,n){var i=n(35);e.exports=function(e,t){if(!i(e))return e;var n,r;if(t&&"function"==typeof(n=e.toString)&&!i(r=n.call(e)))return r;if("function"==typeof(n=e.valueOf)&&!i(r=n.call(e)))return r;if(!t&&"function"==typeof(n=e.toString)&&!i(r=n.call(e)))return r;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){var i=n(18),r=n(11),o=n(58),a=n(67),s=n(19).f;e.exports=function(e){var t=r.Symbol||(r.Symbol=o?{}:i.Symbol||{});"_"==e.charAt(0)||e in t||s(t,e,{value:a.f(e)})}},function(e,t,n){t.f=n(12)},function(e,t,n){n(261);for(var i=n(18),r=n(28),o=n(29),a=n(12)("toStringTag"),s=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],l=0;l<5;l++){var u=s[l],c=i[u],d=c&&c.prototype;d&&!d[a]&&r(d,a,u),o[u]=o.Array}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(6),s=i(a),l=n(1),u=i(l),c=n(5),d=i(c),f=n(70),p=u["default"].createClass({displayName:"TabContent",propTypes:{animated:l.PropTypes.bool,prefixCls:l.PropTypes.string,children:l.PropTypes.any,activeKey:l.PropTypes.string,style:l.PropTypes.any,tabBarPosition:l.PropTypes.string},getDefaultProps:function(){return{animated:!0}},getTabPanes:function(){var e=this.props,t=e.activeKey,n=e.children,i=[];return u["default"].Children.forEach(n,function(n){if(n){var r=n.key,o=t===r;i.push(u["default"].cloneElement(n,{active:o,destroyInactiveTabPane:e.destroyInactiveTabPane,rootPrefixCls:e.prefixCls}))}}),i},render:function(){var e,t=this.props,n=t.prefixCls,i=t.children,r=t.activeKey,a=t.tabBarPosition,l=t.animated,c=t.style,p=(0,d["default"])((e={},(0,s["default"])(e,n+"-content",!0),(0,s["default"])(e,l?n+"-content-animated":n+"-content-no-animated",!0),e));if(l){var h=(0,f.getActiveIndex)(i,r);c=h!==-1?(0,o["default"])({},c,(0,f.getTransformPropValue)((0,f.getTransformByIndex)(h,a))):(0,o["default"])({},c,{display:"none"})}return u["default"].createElement("div",{className:p,style:c},this.getTabPanes())}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){if(Array.isArray(e))return e.filter(function(e){return!!e});var t=[];return h["default"].Children.forEach(e,function(e){e&&t.push(e)}),t}function o(e,t){var n=-1;return h["default"].Children.forEach(e,function(e,i){e.key===t&&(n=i)}),n}function a(e,t){var n=r(e);return n[t].key}function s(e,t){e.transform=t,e.webkitTransform=t,e.mozTransform=t}function l(e){return"transform"in e||"webkitTransform"in e||"MozTransform"in e}function u(e,t){e.transition=t,e.webkitTransition=t,e.MozTransition=t}function c(e){return{transform:e,WebkitTransform:e,MozTransform:e}}function d(e){return"left"===e||"right"===e}function f(e,t){var n=d(t)?"translateY":"translateX";return n+"("+100*-e+"%) translateZ(0)"}Object.defineProperty(t,"__esModule",{value:!0}),t.toArray=r,t.getActiveIndex=o,t.getActiveKey=a,t.setTransform=s,t.isTransformSupported=l,t.setTransition=u,t.getTransformPropValue=c,t.isVertical=d,t.getTransformByIndex=f;var p=n(1),h=i(p)},function(e,t,n){function i(e,t){t.hasOwnProperty("vertical")&&console.warn("vertical is deprecated, please use `direction` instead");var n=t.direction;(n||t.hasOwnProperty("vertical"))&&(direction=n?n:t.vertical?"DIRECTION_ALL":"DIRECTION_HORIZONTAL",e.get("pan").set({direction:a[direction]}),e.get("swipe").set({direction:a[direction]})),t.options&&Object.keys(t.options).forEach(function(n){if("recognizers"===n)Object.keys(t.options.recognizers).forEach(function(n){var i=e.get(n);i.set(t.options.recognizers[n])},this);else{var i=n,r={};r[i]=t.options[n],e.set(r)}},this),t.recognizeWith&&Object.keys(t.recognizeWith).forEach(function(n){var i=e.get(n);i.recognizeWith(t.recognizeWith[n])},this),Object.keys(t).forEach(function(n){var i=l[n];i&&(e.off(i),e.on(i,t[n]))})}var r=n(1),o=n(9),a="undefined"!=typeof window?n(329):void 0,s={children:!0,direction:!0,options:!0,recognizeWith:!0,vertical:!0},l={action:"tap press",onDoubleTap:"doubletap",onPan:"pan",onPanCancel:"pancancel",onPanEnd:"panend",onPanStart:"panstart",onPinch:"pinch",onPinchCancel:"pinchcancel",onPinchEnd:"pinchend",onPinchIn:"pinchin",onPinchOut:"pinchout",onPinchStart:"pinchstart",onPress:"press",onPressUp:"pressup",onRotate:"rotate",onRotateCancel:"rotatecancel",onRotateEnd:"rotateend",onRotateMove:"rotatemove",onRotateStart:"rotatestart",onSwipe:"swipe",onTap:"tap"};Object.keys(l).forEach(function(e){s[e]=!0});var u=r.createClass({displayName:"Hammer",propTypes:{className:r.PropTypes.string},componentDidMount:function(){this.hammer=new a(o.findDOMNode(this)),i(this.hammer,this.props)},componentDidUpdate:function(){this.hammer&&i(this.hammer,this.props)},componentWillUnmount:function(){this.hammer&&(this.hammer.stop(),this.hammer.destroy()),this.hammer=null},render:function(){var e={};return Object.keys(this.props).forEach(function(t){s[t]||(e[t]=this.props[t])},this),r.cloneElement(r.Children.only(this.props.children),e)}});e.exports=u},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(116),o=i(r),a=n(418),s=i(a),l=n(421),u=i(l);o["default"].IndexedList=s["default"],o["default"].RefreshControl=u["default"],t["default"]=o["default"],e.exports=t["default"]},function(e,t){"use strict";function n(e){var t=0;do isNaN(e.offsetTop)||(t+=e.offsetTop);while(e=e.offsetParent);return t}function i(e){return e.touches&&e.touches.length?e.touches[0]:e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:e}function r(e,t){var n=!0;return function(i){n&&(n=!1,setTimeout(function(){n=!0},t),e(i))}}Object.defineProperty(t,"__esModule",{value:!0}),t.getOffsetTop=n,t._event=i,t.throttle=r},function(e,t){function n(e,t,n){n=n||{},n.childrenKeyName=n.childrenKeyName||"children";var i,r=e||[],o=[],a=0;do{var i=r.filter(function(e){return t(e,a)})[0];if(!i)break;o.push(i),r=i[n.childrenKeyName]||[],a+=1}while(r.length>0);return o}e.exports=n},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e), t.prototype.render=function(){var e,t,n=this.props,i=n.text,r=n.prefixCls,a=n.overflowCount,s=n.className,l=n.style,u=n.children,c=this.props.dot,d=this.props.size,f=this.props.corner;i=i>a?a+"+":i,c&&(i="");var h=!(i&&"0"!==i||c),y=(0,m["default"])((e={},(0,o["default"])(e,r+"-dot",c),(0,o["default"])(e,r+"-dot-large",c&&"large"===d),(0,o["default"])(e,r+"-text",!c&&!f),(0,o["default"])(e,r+"-corner",f),(0,o["default"])(e,r+"-corner-large",f&&"large"===d),e)),v=(0,m["default"])((t={},(0,o["default"])(t,s,!!s),(0,o["default"])(t,r,!0),(0,o["default"])(t,r+"-not-a-wrapper",!u),(0,o["default"])(t,r+"-corner-wrapper",f),(0,o["default"])(t,r+"-corner-wrapper-large",f&&"large"===d),t));return p["default"].createElement("span",{className:v,title:i},u,!h&&p["default"].createElement("sup",{className:y,style:l},i))},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-badge",text:null,dot:!1,corner:!1,overflowCount:99,size:null},e.exports=t["default"]},[451,283],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(6),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(5),v=i(y),g=n(336),b=i(g),M=n(10),T=i(M),x=function(e){function t(n){(0,u["default"])(this,t);var i=(0,d["default"])(this,e.call(this,n));return i.state={selectedIndex:i.props.selectedIndex},i.onChange=i.onChange.bind(i),i}return(0,p["default"])(t,e),t.prototype.onChange=function(e){this.setState({selectedIndex:e})},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.children,i=this.state.selectedIndex,r=void 0;if(!n)return null;var a=(0,T["default"])({},this.props);a.infinite&&(a.wrapAround=!0),a.selectedIndex&&(a.slideIndex=a.selectedIndex),a.beforeChange&&(a.beforeSlide=a.beforeChange),a.afterChange&&(a.afterSlide=a.afterChange),a.vertical&&(r=a.prefixCls+" "+a.prefixCls+"-vertical");var l=[];return a.dots&&(l=[{component:m["default"].createClass({displayName:"component",render:function(){var e=this,n=this.getIndexes(e.props.slideCount,e.props.slidesToScroll);return m["default"].createElement("div",{className:t+"-wrap"},n.map(function(e){var n,r=(0,v["default"])((n={},(0,s["default"])(n,t+"-wrap-dot",!0),(0,s["default"])(n,t+"-wrap-dot-active",e===i),n));return m["default"].createElement("div",{className:r,key:e},m["default"].createElement("span",null))}))},getIndexes:function(e,t){for(var n=[],i=0;i<e;i+=t)n.push(i);return n}}),position:"BottomCenter"}]),m["default"].createElement("div",{className:r},m["default"].createElement(b["default"],(0,o["default"])({},a,{decorators:l,afterSlide:this.onChange})))},t}(m["default"].Component);t["default"]=x,x.defaultProps={prefixCls:"am-carousel",dots:!0,arrows:!1,autoplay:!1,infinite:!1,edgeEasing:"linear",cellAlign:"center",selectedIndex:0},e.exports=t["default"]},[451,286],[453,287],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n=(0,c["default"])(e,["renderHeader","renderFooter","renderSectionHeader","renderRow"]),i=(0,a["default"])(n,2),r=i[0],o=r.renderHeader,s=r.renderFooter,u=r.renderSectionHeader,d=r.renderRow,f=i[1],h=e.listPrefixCls,m={renderHeader:null,renderFooter:null,renderSectionHeader:null,renderBodyComponent:function(){return l["default"].createElement("div",{className:h+"-body"})},renderRow:d};return o&&(m.renderHeader=function(){return l["default"].createElement("div",{className:h+"-header"},o())}),s&&(m.renderFooter=function(){return l["default"].createElement("div",{className:h+"-footer"},s())}),u&&(m.renderSectionHeader=t?function(e,t){return l["default"].createElement("div",null,l["default"].createElement(p,null,u(e,t)))}:function(e,t){return l["default"].createElement(p,null,u(e,t))}),{restProps:f,extraProps:m}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(14),a=i(o);t["default"]=r;var s=n(1),l=i(s),u=n(15),c=i(u),d=n(26),f=i(d),p=f["default"].Item;e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(50),o=i(r),a=n(163),s=i(a),l=n(164),u=i(l);o["default"].alert=s["default"],o["default"].prompt=u["default"],t["default"]=o["default"],e.exports=t["default"]},[451,297],[451,301],[453,305],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){return f=u["default"].newInstance({prefixCls:p,style:{top:0},transitionName:"am-fade"})}function o(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,i=arguments[3],o={info:"",success:"check-circle-o",fail:"cross-circle-o",offline:"frown",loading:"loading"}[t];"function"==typeof n&&(i=n,n=3);var a=r();a.notice({duration:n,style:{},content:o?s["default"].createElement("div",{className:p+"-text "+p+"-text-icon"},s["default"].createElement(d["default"],{type:o,size:"lg"}),s["default"].createElement("div",{className:p+"-text-info"},e)):s["default"].createElement("div",{className:p+"-text"},s["default"].createElement("div",null,e)),onClose:function(){i&&i(),a.destroy(),a=null,f=null}})}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=i(a),l=n(367),u=i(l),c=n(13),d=i(c),f=void 0,p="am-toast";t["default"]={SHORT:3,LONG:8,show:function(e,t){return o(e,"info",t,function(){})},info:function(e,t,n){return o(e,"info",t,n)},success:function(e,t,n){return o(e,"success",t,n)},fail:function(e,t,n){return o(e,"fail",t,n)},offline:function(e,t,n){return o(e,"offline",t,n)},loading:function(e,t,n){return o(e,"loading",t,n)},hide:function(){f&&(f.destroy(),f=null)}},e.exports=t["default"]},[452,321],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(2),o=i(r),a=n(4),s=i(a),l=n(3),u=i(l),c=n(1),d=i(c),f=n(10),p=i(f),h=function(e){function t(){return(0,o["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){var e=(0,p["default"])({},this.props);Array.isArray(e.style)&&!function(){var t={};e.style.forEach(function(e){(0,p["default"])(t,e)}),e.style=t}();var t=e.Component;return d["default"].createElement(t,e)},t}(d["default"].Component);t["default"]=h,h.defaultProps={Component:"div"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.size,r=t.className,a=t.children,s=t.style,l=(0,m["default"])((e={},(0,o["default"])(e,""+n,!0),(0,o["default"])(e,n+"-"+i,!0),(0,o["default"])(e,r,!!r),e));return p["default"].createElement("div",{className:l,style:s},a)},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-wingblank",size:"lg"},e.exports=t["default"]},[451,323],function(e,t){e.exports=function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;n<e.length;++n)if(e[n]===t)return n;return-1}},function(e,t,n){var i=n(54),r=n(12)("toStringTag"),o="Arguments"==i(function(){return arguments}()),a=function(e,t){try{return e[t]}catch(n){}};e.exports=function(e){var t,n,s;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=a(t=Object(e),r))?n:o?i(t):"Object"==(s=i(t))&&"function"==typeof t.callee?"Arguments":s}},function(e,t,n){var i=n(35),r=n(18).document,o=i(r)&&i(r.createElement);e.exports=function(e){return o?r.createElement(e):{}}},function(e,t,n){e.exports=!n(22)&&!n(27)(function(){return 7!=Object.defineProperty(n(92)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var i=n(54);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==i(e)?e.split(""):Object(e)}},function(e,t,n){"use strict";var i=n(58),r=n(17),o=n(99),a=n(28),s=n(23),l=n(29),u=n(245),c=n(61),d=n(253),f=n(12)("iterator"),p=!([].keys&&"next"in[].keys()),h="@@iterator",m="keys",y="values",v=function(){return this};e.exports=function(e,t,n,g,b,M,T){u(n,t,g);var x,C,_,w=function(e){if(!p&&e in P)return P[e];switch(e){case m:return function(){return new n(this,e)};case y:return function(){return new n(this,e)}}return function(){return new n(this,e)}},S=t+" Iterator",N=b==y,E=!1,P=e.prototype,D=P[f]||P[h]||b&&P[b],I=D||w(b),L=b?N?w("entries"):I:void 0,j="Array"==t?P.entries||D:D;if(j&&(_=d(j.call(new e)),_!==Object.prototype&&(c(_,S,!0),i||s(_,f)||a(_,f,v))),N&&D&&D.name!==y&&(E=!0,I=function(){return D.call(this)}),i&&!T||!p&&!E&&P[f]||a(P,f,I),l[t]=I,l[S]=v,b)if(x={values:N?I:w(y),keys:M?I:w(m),entries:L},T)for(C in x)C in P||o(P,C,x[C]);else r(r.P+r.F*(p||E),t,x);return x}},function(e,t,n){var i=n(41),r=n(36),o=n(24),a=n(65),s=n(23),l=n(93),u=Object.getOwnPropertyDescriptor;t.f=n(22)?u:function(e,t){if(e=o(e),t=a(t,!0),l)try{return u(e,t)}catch(n){}if(s(e,t))return r(!i.f.call(e,t),e[t])}},function(e,t,n){var i=n(98),r=n(57).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return i(e,r)}},function(e,t,n){var i=n(23),r=n(24),o=n(238)(!1),a=n(62)("IE_PROTO");e.exports=function(e,t){var n,s=r(e),l=0,u=[];for(n in s)n!=a&&i(s,n)&&u.push(n);for(;t.length>l;)i(s,n=t[l++])&&(~o(u,n)||u.push(n));return u}},function(e,t,n){e.exports=n(28)},function(e,t,n){var i=n(64),r=Math.min;e.exports=function(e){return e>0?r(i(e),9007199254740991):0}},function(e,t,n){var i=n(91),r=n(12)("iterator"),o=n(29);e.exports=n(11).getIteratorMethod=function(e){if(void 0!=e)return e[r]||e["@@iterator"]||o[i(e)]}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){for(var n=window.getComputedStyle(e),i="",r=0;r<h.length&&!(i=n.getPropertyValue(h[r]+t));r++);return i}function o(e){if(f){var t=parseFloat(r(e,"transition-delay"))||0,n=parseFloat(r(e,"transition-duration"))||0,i=parseFloat(r(e,"animation-delay"))||0,o=parseFloat(r(e,"animation-duration"))||0,a=Math.max(n+t,o+i);e.rcEndAnimTimeout=setTimeout(function(){e.rcEndAnimTimeout=null,e.rcEndListener&&e.rcEndListener()},1e3*a+200)}}function a(e){e.rcEndAnimTimeout&&(clearTimeout(e.rcEndAnimTimeout),e.rcEndAnimTimeout=null)}Object.defineProperty(t,"__esModule",{value:!0});var s="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},l=n(271),u=i(l),c=n(225),d=i(c),f=0!==u["default"].endEvents.length,p=["Webkit","Moz","O","ms"],h=["-webkit-","-moz-","-o-","ms-",""],m=function(e,t,n){var i="object"===("undefined"==typeof t?"undefined":s(t)),r=i?t.name:t,l=i?t.active:t+"-active",c=n,f=void 0,p=void 0,h=(0,d["default"])(e);return n&&"[object Object]"===Object.prototype.toString.call(n)&&(c=n.end,f=n.start,p=n.active),e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),a(e),h.remove(r),h.remove(l),u["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,c&&c())},u["default"].addEndEventListener(e,e.rcEndListener),f&&f(),h.add(r),e.rcAnimTimeout=setTimeout(function(){e.rcAnimTimeout=null,h.add(l),p&&setTimeout(p,0),o(e)},30),{stop:function(){e.rcEndListener&&e.rcEndListener()}}};m.style=function(e,t,n){e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),a(e),u["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,n&&n())},u["default"].addEndEventListener(e,e.rcEndListener),e.rcAnimTimeout=setTimeout(function(){for(var n in t)t.hasOwnProperty(n)&&(e.style[n]=t[n]);e.rcAnimTimeout=null,o(e)},0)},m.setTransition=function(e,t,n){var i=t,r=n;void 0===n&&(r=i,i=""),i=i||"",p.forEach(function(t){e.style[t+"Transition"+i]=r})},m.isCssAnimationSupported=f,t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.ownerDocument,n=t.body,i=void 0,r=a["default"].css(e,"position"),o="fixed"===r||"absolute"===r;if(!o)return"html"===e.nodeName.toLowerCase()?null:e.parentNode;for(i=e.parentNode;i&&i!==n;i=i.parentNode)if(r=a["default"].css(i,"position"),"static"!==r)return i;return null}Object.defineProperty(t,"__esModule",{value:!0});var o=n(37),a=i(o);t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function i(e,t,n,i,r,o,a,s){if(!e){var l;if(void 0===t)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[n,i,r,o,a,s],c=0;l=new Error(t.replace(/%s/g,function(){return u[c++]})),l.name="Invariant Violation"}throw l.framesToPop=1,l}}e.exports=i},function(e,t,n){"use strict";var i=n(325),r=i;e.exports=r},function(e,t){!function(n,i){"object"==typeof t&&"undefined"!=typeof e?e.exports=i():"function"==typeof define&&define.amd?define(i):n.moment=i()}(this,function(){"use strict";function t(){return hi.apply(null,arguments)}function n(e){hi=e}function i(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function r(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function o(e){var t;for(t in e)return!1;return!0}function a(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function s(e,t){var n,i=[];for(n=0;n<e.length;++n)i.push(t(e[n],n));return i}function l(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function u(e,t){for(var n in t)l(t,n)&&(e[n]=t[n]);return l(t,"toString")&&(e.toString=t.toString),l(t,"valueOf")&&(e.valueOf=t.valueOf),e}function c(e,t,n,i){return vt(e,t,n,i,!0).utc()}function d(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null}}function f(e){return null==e._pf&&(e._pf=d()),e._pf}function p(e){if(null==e._isValid){var t=f(e),n=mi.call(t.parsedDateParts,function(e){return null!=e}),i=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidMonth&&!t.invalidWeekday&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(i=i&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return i;e._isValid=i}return e._isValid}function h(e){var t=c(NaN);return null!=e?u(f(t),e):f(t).userInvalidated=!0,t}function m(e){return void 0===e}function y(e,t){var n,i,r;if(m(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),m(t._i)||(e._i=t._i),m(t._f)||(e._f=t._f),m(t._l)||(e._l=t._l),m(t._strict)||(e._strict=t._strict),m(t._tzm)||(e._tzm=t._tzm),m(t._isUTC)||(e._isUTC=t._isUTC),m(t._offset)||(e._offset=t._offset),m(t._pf)||(e._pf=f(t)),m(t._locale)||(e._locale=t._locale),yi.length>0)for(n in yi)i=yi[n],r=t[i],m(r)||(e[i]=r);return e}function v(e){y(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),vi===!1&&(vi=!0,t.updateOffset(this),vi=!1)}function g(e){return e instanceof v||null!=e&&null!=e._isAMomentObject}function b(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function M(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=b(t)),n}function T(e,t,n){var i,r=Math.min(e.length,t.length),o=Math.abs(e.length-t.length),a=0;for(i=0;i<r;i++)(n&&e[i]!==t[i]||!n&&M(e[i])!==M(t[i]))&&a++;return a+o}function x(e){t.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function C(e,n){var i=!0;return u(function(){if(null!=t.deprecationHandler&&t.deprecationHandler(null,e),i){for(var r,o=[],a=0;a<arguments.length;a++){if(r="","object"==typeof arguments[a]){r+="\n["+a+"] ";for(var s in arguments[0])r+=s+": "+arguments[0][s]+", ";r=r.slice(0,-2)}else r=arguments[a];o.push(r)}x(e+"\nArguments: "+Array.prototype.slice.call(o).join("")+"\n"+(new Error).stack),i=!1}return n.apply(this,arguments)},n)}function _(e,n){null!=t.deprecationHandler&&t.deprecationHandler(e,n),gi[e]||(x(n),gi[e]=!0)}function w(e){return e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function S(e){var t,n;for(n in e)t=e[n],w(t)?this[n]=t:this["_"+n]=t;this._config=e,this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function N(e,t){var n,i=u({},e);for(n in t)l(t,n)&&(r(e[n])&&r(t[n])?(i[n]={},u(i[n],e[n]),u(i[n],t[n])):null!=t[n]?i[n]=t[n]:delete i[n]);for(n in e)l(e,n)&&!l(t,n)&&r(e[n])&&(i[n]=u({},i[n]));return i}function E(e){null!=e&&this.set(e)}function P(e,t,n){var i=this._calendar[e]||this._calendar.sameElse;return w(i)?i.call(t,n):i}function D(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])}function I(){return this._invalidDate}function L(e){return this._ordinal.replace("%d",e)}function j(e,t,n,i){var r=this._relativeTime[n];return w(r)?r(e,t,n,i):r.replace(/%d/i,e)}function k(e,t){var n=this._relativeTime[e>0?"future":"past"];return w(n)?n(t):n.replace(/%s/i,t)}function O(e,t){var n=e.toLowerCase();Ni[n]=Ni[n+"s"]=Ni[t]=e}function A(e){return"string"==typeof e?Ni[e]||Ni[e.toLowerCase()]:void 0}function z(e){var t,n,i={};for(n in e)l(e,n)&&(t=A(n),t&&(i[t]=e[n]));return i}function R(e,t){Ei[e]=t}function W(e){var t=[];for(var n in e)t.push({unit:n,priority:Ei[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}function Y(e,n){return function(i){return null!=i?(B(this,e,i),t.updateOffset(this,n),this):H(this,e)}}function H(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function B(e,t,n){e.isValid()&&e._d["set"+(e._isUTC?"UTC":"")+t](n)}function U(e){return e=A(e),w(this[e])?this[e]():this}function F(e,t){if("object"==typeof e){e=z(e);for(var n=W(e),i=0;i<n.length;i++)this[n[i].unit](e[n[i].unit])}else if(e=A(e),w(this[e]))return this[e](t);return this}function V(e,t,n){var i=""+Math.abs(e),r=t-i.length,o=e>=0;return(o?n?"+":"":"-")+Math.pow(10,Math.max(0,r)).toString().substr(1)+i}function Q(e,t,n,i){var r=i;"string"==typeof i&&(r=function(){return this[i]()}),e&&(Li[e]=r),t&&(Li[t[0]]=function(){return V(r.apply(this,arguments),t[1],t[2])}),n&&(Li[n]=function(){return this.localeData().ordinal(r.apply(this,arguments),e)})}function G(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function Z(e){var t,n,i=e.match(Pi);for(t=0,n=i.length;t<n;t++)Li[i[t]]?i[t]=Li[i[t]]:i[t]=G(i[t]);return function(t){var r,o="";for(r=0;r<n;r++)o+=i[r]instanceof Function?i[r].call(t,e):i[r];return o}}function X(e,t){return e.isValid()?(t=J(t,e.localeData()),Ii[t]=Ii[t]||Z(t),Ii[t](e)):e.localeData().invalidDate()}function J(e,t){function n(e){return t.longDateFormat(e)||e}var i=5;for(Di.lastIndex=0;i>=0&&Di.test(e);)e=e.replace(Di,n),Di.lastIndex=0,i-=1;return e}function K(e,t,n){Ji[e]=w(t)?t:function(e,i){return e&&n?n:t}}function q(e,t){return l(Ji,e)?Ji[e](t._strict,t._locale):new RegExp($(e))}function $(e){return ee(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,i,r){return t||n||i||r}))}function ee(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function te(e,t){var n,i=t;for("string"==typeof e&&(e=[e]),"number"==typeof t&&(i=function(e,n){n[t]=M(e)}),n=0;n<e.length;n++)Ki[e[n]]=i}function ne(e,t){te(e,function(e,n,i,r){i._w=i._w||{},t(e,i._w,i,r)})}function ie(e,t,n){null!=t&&l(Ki,e)&&Ki[e](t,n._a,n,e)}function re(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function oe(e,t){return e?i(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||sr).test(t)?"format":"standalone"][e.month()]:this._months}function ae(e,t){return e?i(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[sr.test(t)?"format":"standalone"][e.month()]:this._monthsShort}function se(e,t,n){var i,r,o,a=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],i=0;i<12;++i)o=c([2e3,i]),this._shortMonthsParse[i]=this.monthsShort(o,"").toLocaleLowerCase(),this._longMonthsParse[i]=this.months(o,"").toLocaleLowerCase();return n?"MMM"===t?(r=Mi.call(this._shortMonthsParse,a),r!==-1?r:null):(r=Mi.call(this._longMonthsParse,a),r!==-1?r:null):"MMM"===t?(r=Mi.call(this._shortMonthsParse,a),r!==-1?r:(r=Mi.call(this._longMonthsParse,a),r!==-1?r:null)):(r=Mi.call(this._longMonthsParse,a),r!==-1?r:(r=Mi.call(this._shortMonthsParse,a),r!==-1?r:null))}function le(e,t,n){var i,r,o;if(this._monthsParseExact)return se.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),i=0;i<12;i++){if(r=c([2e3,i]),n&&!this._longMonthsParse[i]&&(this._longMonthsParse[i]=new RegExp("^"+this.months(r,"").replace(".","")+"$","i"),this._shortMonthsParse[i]=new RegExp("^"+this.monthsShort(r,"").replace(".","")+"$","i")),n||this._monthsParse[i]||(o="^"+this.months(r,"")+"|^"+this.monthsShort(r,""),this._monthsParse[i]=new RegExp(o.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[i].test(e))return i;if(n&&"MMM"===t&&this._shortMonthsParse[i].test(e))return i;if(!n&&this._monthsParse[i].test(e))return i}}function ue(e,t){var n;if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=M(t);else if(t=e.localeData().monthsParse(t),"number"!=typeof t)return e;return n=Math.min(e.date(),re(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n),e}function ce(e){return null!=e?(ue(this,e),t.updateOffset(this,!0),this):H(this,"Month")}function de(){return re(this.year(),this.month())}function fe(e){return this._monthsParseExact?(l(this,"_monthsRegex")||he.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(l(this,"_monthsShortRegex")||(this._monthsShortRegex=cr),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)}function pe(e){return this._monthsParseExact?(l(this,"_monthsRegex")||he.call(this),e?this._monthsStrictRegex:this._monthsRegex):(l(this,"_monthsRegex")||(this._monthsRegex=dr),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)}function he(){function e(e,t){return t.length-e.length}var t,n,i=[],r=[],o=[];for(t=0;t<12;t++)n=c([2e3,t]),i.push(this.monthsShort(n,"")),r.push(this.months(n,"")),o.push(this.months(n,"")),o.push(this.monthsShort(n,""));for(i.sort(e),r.sort(e),o.sort(e),t=0;t<12;t++)i[t]=ee(i[t]),r[t]=ee(r[t]);for(t=0;t<24;t++)o[t]=ee(o[t]);this._monthsRegex=new RegExp("^("+o.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+i.join("|")+")","i")}function me(e){return ye(e)?366:365}function ye(e){return e%4===0&&e%100!==0||e%400===0}function ve(){return ye(this.year())}function ge(e,t,n,i,r,o,a){var s=new Date(e,t,n,i,r,o,a);return e<100&&e>=0&&isFinite(s.getFullYear())&&s.setFullYear(e),s}function be(e){var t=new Date(Date.UTC.apply(null,arguments));return e<100&&e>=0&&isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e),t}function Me(e,t,n){var i=7+t-n,r=(7+be(e,0,i).getUTCDay()-t)%7;return-r+i-1}function Te(e,t,n,i,r){var o,a,s=(7+n-i)%7,l=Me(e,i,r),u=1+7*(t-1)+s+l;return u<=0?(o=e-1,a=me(o)+u):u>me(e)?(o=e+1,a=u-me(e)):(o=e,a=u),{year:o,dayOfYear:a}}function xe(e,t,n){var i,r,o=Me(e.year(),t,n),a=Math.floor((e.dayOfYear()-o-1)/7)+1;return a<1?(r=e.year()-1,i=a+Ce(r,t,n)):a>Ce(e.year(),t,n)?(i=a-Ce(e.year(),t,n),r=e.year()+1):(r=e.year(),i=a),{week:i,year:r}}function Ce(e,t,n){var i=Me(e,t,n),r=Me(e+1,t,n);return(me(e)-i+r)/7}function _e(e){return xe(e,this._week.dow,this._week.doy).week}function we(){return this._week.dow}function Se(){return this._week.doy}function Ne(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")}function Ee(e){var t=xe(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")}function Pe(e,t){return"string"!=typeof e?e:isNaN(e)?(e=t.weekdaysParse(e),"number"==typeof e?e:null):parseInt(e,10)}function De(e,t){return"string"==typeof e?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}function Ie(e,t){return e?i(this._weekdays)?this._weekdays[e.day()]:this._weekdays[this._weekdays.isFormat.test(t)?"format":"standalone"][e.day()]:this._weekdays}function Le(e){return e?this._weekdaysShort[e.day()]:this._weekdaysShort}function je(e){return e?this._weekdaysMin[e.day()]:this._weekdaysMin}function ke(e,t,n){var i,r,o,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],i=0;i<7;++i)o=c([2e3,1]).day(i),this._minWeekdaysParse[i]=this.weekdaysMin(o,"").toLocaleLowerCase(),this._shortWeekdaysParse[i]=this.weekdaysShort(o,"").toLocaleLowerCase(),this._weekdaysParse[i]=this.weekdays(o,"").toLocaleLowerCase();return n?"dddd"===t?(r=Mi.call(this._weekdaysParse,a),r!==-1?r:null):"ddd"===t?(r=Mi.call(this._shortWeekdaysParse,a),r!==-1?r:null):(r=Mi.call(this._minWeekdaysParse,a),r!==-1?r:null):"dddd"===t?(r=Mi.call(this._weekdaysParse,a),r!==-1?r:(r=Mi.call(this._shortWeekdaysParse,a),r!==-1?r:(r=Mi.call(this._minWeekdaysParse,a),r!==-1?r:null))):"ddd"===t?(r=Mi.call(this._shortWeekdaysParse,a),r!==-1?r:(r=Mi.call(this._weekdaysParse,a),r!==-1?r:(r=Mi.call(this._minWeekdaysParse,a),r!==-1?r:null))):(r=Mi.call(this._minWeekdaysParse,a),r!==-1?r:(r=Mi.call(this._weekdaysParse,a),r!==-1?r:(r=Mi.call(this._shortWeekdaysParse,a),r!==-1?r:null)))}function Oe(e,t,n){var i,r,o;if(this._weekdaysParseExact)return ke.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),i=0;i<7;i++){if(r=c([2e3,1]).day(i),n&&!this._fullWeekdaysParse[i]&&(this._fullWeekdaysParse[i]=new RegExp("^"+this.weekdays(r,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[i]=new RegExp("^"+this.weekdaysShort(r,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[i]=new RegExp("^"+this.weekdaysMin(r,"").replace(".",".?")+"$","i")),this._weekdaysParse[i]||(o="^"+this.weekdays(r,"")+"|^"+this.weekdaysShort(r,"")+"|^"+this.weekdaysMin(r,""),this._weekdaysParse[i]=new RegExp(o.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[i].test(e))return i;if(n&&"ddd"===t&&this._shortWeekdaysParse[i].test(e))return i;if(n&&"dd"===t&&this._minWeekdaysParse[i].test(e))return i;if(!n&&this._weekdaysParse[i].test(e))return i}}function Ae(e){if(!this.isValid())return null!=e?this:NaN;var t=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(e=Pe(e,this.localeData()),this.add(e-t,"d")):t}function ze(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")}function Re(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=De(e,this.localeData());return this.day(this.day()%7?t:t-7)}return this.day()||7}function We(e){return this._weekdaysParseExact?(l(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(l(this,"_weekdaysRegex")||(this._weekdaysRegex=vr),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)}function Ye(e){return this._weekdaysParseExact?(l(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(l(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=gr),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function He(e){return this._weekdaysParseExact?(l(this,"_weekdaysRegex")||Be.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(l(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=br),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function Be(){function e(e,t){return t.length-e.length}var t,n,i,r,o,a=[],s=[],l=[],u=[];for(t=0;t<7;t++)n=c([2e3,1]).day(t),i=this.weekdaysMin(n,""),r=this.weekdaysShort(n,""),o=this.weekdays(n,""),a.push(i),s.push(r),l.push(o),u.push(i),u.push(r),u.push(o);for(a.sort(e),s.sort(e),l.sort(e),u.sort(e),t=0;t<7;t++)s[t]=ee(s[t]),l[t]=ee(l[t]),u[t]=ee(u[t]);this._weekdaysRegex=new RegExp("^("+u.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+a.join("|")+")","i")}function Ue(){return this.hours()%12||12}function Fe(){return this.hours()||24}function Ve(e,t){Q(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function Qe(e,t){return t._meridiemParse}function Ge(e){return"p"===(e+"").toLowerCase().charAt(0)}function Ze(e,t,n){return e>11?n?"pm":"PM":n?"am":"AM"}function Xe(e){return e?e.toLowerCase().replace("_","-"):e}function Je(e){for(var t,n,i,r,o=0;o<e.length;){for(r=Xe(e[o]).split("-"),t=r.length,n=Xe(e[o+1]),n=n?n.split("-"):null;t>0;){if(i=Ke(r.slice(0,t).join("-")))return i;if(n&&n.length>=t&&T(r,n,!0)>=t-1)break;t--}o++}return null}function Ke(t){var n=null;if(!_r[t]&&"undefined"!=typeof e&&e&&e.exports)try{n=Mr._abbr,require("./locale/"+t),qe(n)}catch(i){}return _r[t]}function qe(e,t){var n;return e&&(n=m(t)?tt(e):$e(e,t),n&&(Mr=n)),Mr._abbr}function $e(e,t){if(null!==t){var n=Cr;return t.abbr=e,null!=_r[e]?(_("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),n=_r[e]._config):null!=t.parentLocale&&(null!=_r[t.parentLocale]?n=_r[t.parentLocale]._config:_("parentLocaleUndefined","specified parentLocale is not defined yet. See http://momentjs.com/guides/#/warnings/parent-locale/")),_r[e]=new E(N(n,t)),qe(e),_r[e]}return delete _r[e],null}function et(e,t){if(null!=t){var n,i=Cr;null!=_r[e]&&(i=_r[e]._config),t=N(i,t),n=new E(t),n.parentLocale=_r[e],_r[e]=n,qe(e)}else null!=_r[e]&&(null!=_r[e].parentLocale?_r[e]=_r[e].parentLocale:null!=_r[e]&&delete _r[e]);return _r[e]}function tt(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return Mr;if(!i(e)){if(t=Ke(e))return t;e=[e]}return Je(e)}function nt(){return bi(_r)}function it(e){var t,n=e._a;return n&&f(e).overflow===-2&&(t=n[$i]<0||n[$i]>11?$i:n[er]<1||n[er]>re(n[qi],n[$i])?er:n[tr]<0||n[tr]>24||24===n[tr]&&(0!==n[nr]||0!==n[ir]||0!==n[rr])?tr:n[nr]<0||n[nr]>59?nr:n[ir]<0||n[ir]>59?ir:n[rr]<0||n[rr]>999?rr:-1,f(e)._overflowDayOfYear&&(t<qi||t>er)&&(t=er),f(e)._overflowWeeks&&t===-1&&(t=or),f(e)._overflowWeekday&&t===-1&&(t=ar),f(e).overflow=t),e}function rt(e){var t,n,i,r,o,a,s=e._i,l=wr.exec(s)||Sr.exec(s);if(l){for(f(e).iso=!0,t=0,n=Er.length;t<n;t++)if(Er[t][1].exec(l[1])){r=Er[t][0],i=Er[t][2]!==!1;break}if(null==r)return void(e._isValid=!1);if(l[3]){for(t=0,n=Pr.length;t<n;t++)if(Pr[t][1].exec(l[3])){o=(l[2]||" ")+Pr[t][0];break}if(null==o)return void(e._isValid=!1)}if(!i&&null!=o)return void(e._isValid=!1);if(l[4]){if(!Nr.exec(l[4]))return void(e._isValid=!1);a="Z"}e._f=r+(o||"")+(a||""),ct(e)}else e._isValid=!1}function ot(e){var n=Dr.exec(e._i);return null!==n?void(e._d=new Date((+n[1]))):(rt(e),void(e._isValid===!1&&(delete e._isValid,t.createFromInputFallback(e))))}function at(e,t,n){return null!=e?e:null!=t?t:n}function st(e){var n=new Date(t.now());return e._useUTC?[n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()]:[n.getFullYear(),n.getMonth(),n.getDate()]}function lt(e){var t,n,i,r,o=[];if(!e._d){for(i=st(e),e._w&&null==e._a[er]&&null==e._a[$i]&&ut(e),e._dayOfYear&&(r=at(e._a[qi],i[qi]),e._dayOfYear>me(r)&&(f(e)._overflowDayOfYear=!0),n=be(r,0,e._dayOfYear),e._a[$i]=n.getUTCMonth(),e._a[er]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=o[t]=i[t];for(;t<7;t++)e._a[t]=o[t]=null==e._a[t]?2===t?1:0:e._a[t]; 24===e._a[tr]&&0===e._a[nr]&&0===e._a[ir]&&0===e._a[rr]&&(e._nextDay=!0,e._a[tr]=0),e._d=(e._useUTC?be:ge).apply(null,o),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[tr]=24)}}function ut(e){var t,n,i,r,o,a,s,l;t=e._w,null!=t.GG||null!=t.W||null!=t.E?(o=1,a=4,n=at(t.GG,e._a[qi],xe(gt(),1,4).year),i=at(t.W,1),r=at(t.E,1),(r<1||r>7)&&(l=!0)):(o=e._locale._week.dow,a=e._locale._week.doy,n=at(t.gg,e._a[qi],xe(gt(),o,a).year),i=at(t.w,1),null!=t.d?(r=t.d,(r<0||r>6)&&(l=!0)):null!=t.e?(r=t.e+o,(t.e<0||t.e>6)&&(l=!0)):r=o),i<1||i>Ce(n,o,a)?f(e)._overflowWeeks=!0:null!=l?f(e)._overflowWeekday=!0:(s=Te(n,i,r,o,a),e._a[qi]=s.year,e._dayOfYear=s.dayOfYear)}function ct(e){if(e._f===t.ISO_8601)return void rt(e);e._a=[],f(e).empty=!0;var n,i,r,o,a,s=""+e._i,l=s.length,u=0;for(r=J(e._f,e._locale).match(Pi)||[],n=0;n<r.length;n++)o=r[n],i=(s.match(q(o,e))||[])[0],i&&(a=s.substr(0,s.indexOf(i)),a.length>0&&f(e).unusedInput.push(a),s=s.slice(s.indexOf(i)+i.length),u+=i.length),Li[o]?(i?f(e).empty=!1:f(e).unusedTokens.push(o),ie(o,i,e)):e._strict&&!i&&f(e).unusedTokens.push(o);f(e).charsLeftOver=l-u,s.length>0&&f(e).unusedInput.push(s),e._a[tr]<=12&&f(e).bigHour===!0&&e._a[tr]>0&&(f(e).bigHour=void 0),f(e).parsedDateParts=e._a.slice(0),f(e).meridiem=e._meridiem,e._a[tr]=dt(e._locale,e._a[tr],e._meridiem),lt(e),it(e)}function dt(e,t,n){var i;return null==n?t:null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?(i=e.isPM(n),i&&t<12&&(t+=12),i||12!==t||(t=0),t):t}function ft(e){var t,n,i,r,o;if(0===e._f.length)return f(e).invalidFormat=!0,void(e._d=new Date(NaN));for(r=0;r<e._f.length;r++)o=0,t=y({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[r],ct(t),p(t)&&(o+=f(t).charsLeftOver,o+=10*f(t).unusedTokens.length,f(t).score=o,(null==i||o<i)&&(i=o,n=t));u(e,n||t)}function pt(e){if(!e._d){var t=z(e._i);e._a=s([t.year,t.month,t.day||t.date,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),lt(e)}}function ht(e){var t=new v(it(mt(e)));return t._nextDay&&(t.add(1,"d"),t._nextDay=void 0),t}function mt(e){var t=e._i,n=e._f;return e._locale=e._locale||tt(e._l),null===t||void 0===n&&""===t?h({nullInput:!0}):("string"==typeof t&&(e._i=t=e._locale.preparse(t)),g(t)?new v(it(t)):(i(n)?ft(e):a(t)?e._d=t:n?ct(e):yt(e),p(e)||(e._d=null),e))}function yt(e){var n=e._i;void 0===n?e._d=new Date(t.now()):a(n)?e._d=new Date(n.valueOf()):"string"==typeof n?ot(e):i(n)?(e._a=s(n.slice(0),function(e){return parseInt(e,10)}),lt(e)):"object"==typeof n?pt(e):"number"==typeof n?e._d=new Date(n):t.createFromInputFallback(e)}function vt(e,t,n,a,s){var l={};return"boolean"==typeof n&&(a=n,n=void 0),(r(e)&&o(e)||i(e)&&0===e.length)&&(e=void 0),l._isAMomentObject=!0,l._useUTC=l._isUTC=s,l._l=n,l._i=e,l._f=t,l._strict=a,ht(l)}function gt(e,t,n,i){return vt(e,t,n,i,!1)}function bt(e,t){var n,r;if(1===t.length&&i(t[0])&&(t=t[0]),!t.length)return gt();for(n=t[0],r=1;r<t.length;++r)t[r].isValid()&&!t[r][e](n)||(n=t[r]);return n}function Mt(){var e=[].slice.call(arguments,0);return bt("isBefore",e)}function Tt(){var e=[].slice.call(arguments,0);return bt("isAfter",e)}function xt(e){var t=z(e),n=t.year||0,i=t.quarter||0,r=t.month||0,o=t.week||0,a=t.day||0,s=t.hour||0,l=t.minute||0,u=t.second||0,c=t.millisecond||0;this._milliseconds=+c+1e3*u+6e4*l+1e3*s*60*60,this._days=+a+7*o,this._months=+r+3*i+12*n,this._data={},this._locale=tt(),this._bubble()}function Ct(e){return e instanceof xt}function _t(e){return e<0?Math.round(-1*e)*-1:Math.round(e)}function wt(e,t){Q(e,0,0,function(){var e=this.utcOffset(),n="+";return e<0&&(e=-e,n="-"),n+V(~~(e/60),2)+t+V(~~e%60,2)})}function St(e,t){var n=(t||"").match(e)||[],i=n[n.length-1]||[],r=(i+"").match(kr)||["-",0,0],o=+(60*r[1])+M(r[2]);return"+"===r[0]?o:-o}function Nt(e,n){var i,r;return n._isUTC?(i=n.clone(),r=(g(e)||a(e)?e.valueOf():gt(e).valueOf())-i.valueOf(),i._d.setTime(i._d.valueOf()+r),t.updateOffset(i,!1),i):gt(e).local()}function Et(e){return 15*-Math.round(e._d.getTimezoneOffset()/15)}function Pt(e,n){var i,r=this._offset||0;return this.isValid()?null!=e?("string"==typeof e?e=St(Gi,e):Math.abs(e)<16&&(e=60*e),!this._isUTC&&n&&(i=Et(this)),this._offset=e,this._isUTC=!0,null!=i&&this.add(i,"m"),r!==e&&(!n||this._changeInProgress?Vt(this,Yt(e-r,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,t.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?r:Et(this):null!=e?this:NaN}function Dt(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}function It(e){return this.utcOffset(0,e)}function Lt(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Et(this),"m")),this}function jt(){if(this._tzm)this.utcOffset(this._tzm);else if("string"==typeof this._i){var e=St(Qi,this._i);0===e?this.utcOffset(0,!0):this.utcOffset(St(Qi,this._i))}return this}function kt(e){return!!this.isValid()&&(e=e?gt(e).utcOffset():0,(this.utcOffset()-e)%60===0)}function Ot(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function At(){if(!m(this._isDSTShifted))return this._isDSTShifted;var e={};if(y(e,this),e=mt(e),e._a){var t=e._isUTC?c(e._a):gt(e._a);this._isDSTShifted=this.isValid()&&T(e._a,t.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted}function zt(){return!!this.isValid()&&!this._isUTC}function Rt(){return!!this.isValid()&&this._isUTC}function Wt(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}function Yt(e,t){var n,i,r,o=e,a=null;return Ct(e)?o={ms:e._milliseconds,d:e._days,M:e._months}:"number"==typeof e?(o={},t?o[t]=e:o.milliseconds=e):(a=Or.exec(e))?(n="-"===a[1]?-1:1,o={y:0,d:M(a[er])*n,h:M(a[tr])*n,m:M(a[nr])*n,s:M(a[ir])*n,ms:M(_t(1e3*a[rr]))*n}):(a=Ar.exec(e))?(n="-"===a[1]?-1:1,o={y:Ht(a[2],n),M:Ht(a[3],n),w:Ht(a[4],n),d:Ht(a[5],n),h:Ht(a[6],n),m:Ht(a[7],n),s:Ht(a[8],n)}):null==o?o={}:"object"==typeof o&&("from"in o||"to"in o)&&(r=Ut(gt(o.from),gt(o.to)),o={},o.ms=r.milliseconds,o.M=r.months),i=new xt(o),Ct(e)&&l(e,"_locale")&&(i._locale=e._locale),i}function Ht(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function Bt(e,t){var n={milliseconds:0,months:0};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function Ut(e,t){var n;return e.isValid()&&t.isValid()?(t=Nt(t,e),e.isBefore(t)?n=Bt(e,t):(n=Bt(t,e),n.milliseconds=-n.milliseconds,n.months=-n.months),n):{milliseconds:0,months:0}}function Ft(e,t){return function(n,i){var r,o;return null===i||isNaN(+i)||(_(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),o=n,n=i,i=o),n="string"==typeof n?+n:n,r=Yt(n,i),Vt(this,r,e),this}}function Vt(e,n,i,r){var o=n._milliseconds,a=_t(n._days),s=_t(n._months);e.isValid()&&(r=null==r||r,o&&e._d.setTime(e._d.valueOf()+o*i),a&&B(e,"Date",H(e,"Date")+a*i),s&&ue(e,H(e,"Month")+s*i),r&&t.updateOffset(e,a||s))}function Qt(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"}function Gt(e,n){var i=e||gt(),r=Nt(i,this).startOf("day"),o=t.calendarFormat(this,r)||"sameElse",a=n&&(w(n[o])?n[o].call(this,i):n[o]);return this.format(a||this.localeData().calendar(o,this,gt(i)))}function Zt(){return new v(this)}function Xt(e,t){var n=g(e)?e:gt(e);return!(!this.isValid()||!n.isValid())&&(t=A(m(t)?"millisecond":t),"millisecond"===t?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())}function Jt(e,t){var n=g(e)?e:gt(e);return!(!this.isValid()||!n.isValid())&&(t=A(m(t)?"millisecond":t),"millisecond"===t?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())}function Kt(e,t,n,i){return i=i||"()",("("===i[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===i[1]?this.isBefore(t,n):!this.isAfter(t,n))}function qt(e,t){var n,i=g(e)?e:gt(e);return!(!this.isValid()||!i.isValid())&&(t=A(t||"millisecond"),"millisecond"===t?this.valueOf()===i.valueOf():(n=i.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))}function $t(e,t){return this.isSame(e,t)||this.isAfter(e,t)}function en(e,t){return this.isSame(e,t)||this.isBefore(e,t)}function tn(e,t,n){var i,r,o,a;return this.isValid()?(i=Nt(e,this),i.isValid()?(r=6e4*(i.utcOffset()-this.utcOffset()),t=A(t),"year"===t||"month"===t||"quarter"===t?(a=nn(this,i),"quarter"===t?a/=3:"year"===t&&(a/=12)):(o=this-i,a="second"===t?o/1e3:"minute"===t?o/6e4:"hour"===t?o/36e5:"day"===t?(o-r)/864e5:"week"===t?(o-r)/6048e5:o),n?a:b(a)):NaN):NaN}function nn(e,t){var n,i,r=12*(t.year()-e.year())+(t.month()-e.month()),o=e.clone().add(r,"months");return t-o<0?(n=e.clone().add(r-1,"months"),i=(t-o)/(o-n)):(n=e.clone().add(r+1,"months"),i=(t-o)/(n-o)),-(r+i)||0}function rn(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function on(){var e=this.clone().utc();return 0<e.year()&&e.year()<=9999?w(Date.prototype.toISOString)?this.toDate().toISOString():X(e,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):X(e,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function an(e){e||(e=this.isUtc()?t.defaultFormatUtc:t.defaultFormat);var n=X(this,e);return this.localeData().postformat(n)}function sn(e,t){return this.isValid()&&(g(e)&&e.isValid()||gt(e).isValid())?Yt({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function ln(e){return this.from(gt(),e)}function un(e,t){return this.isValid()&&(g(e)&&e.isValid()||gt(e).isValid())?Yt({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function cn(e){return this.to(gt(),e)}function dn(e){var t;return void 0===e?this._locale._abbr:(t=tt(e),null!=t&&(this._locale=t),this)}function fn(){return this._locale}function pn(e){switch(e=A(e)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===e&&this.weekday(0),"isoWeek"===e&&this.isoWeekday(1),"quarter"===e&&this.month(3*Math.floor(this.month()/3)),this}function hn(e){return e=A(e),void 0===e||"millisecond"===e?this:("date"===e&&(e="day"),this.startOf(e).add(1,"isoWeek"===e?"week":e).subtract(1,"ms"))}function mn(){return this._d.valueOf()-6e4*(this._offset||0)}function yn(){return Math.floor(this.valueOf()/1e3)}function vn(){return new Date(this.valueOf())}function gn(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]}function bn(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}}function Mn(){return this.isValid()?this.toISOString():null}function Tn(){return p(this)}function xn(){return u({},f(this))}function Cn(){return f(this).overflow}function _n(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}function wn(e,t){Q(0,[e,e.length],0,t)}function Sn(e){return Dn.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)}function Nn(e){return Dn.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)}function En(){return Ce(this.year(),1,4)}function Pn(){var e=this.localeData()._week;return Ce(this.year(),e.dow,e.doy)}function Dn(e,t,n,i,r){var o;return null==e?xe(this,i,r).year:(o=Ce(e,i,r),t>o&&(t=o),In.call(this,e,t,n,i,r))}function In(e,t,n,i,r){var o=Te(e,t,n,i,r),a=be(o.year,0,o.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}function Ln(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)}function jn(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")}function kn(e,t){t[rr]=M(1e3*("0."+e))}function On(){return this._isUTC?"UTC":""}function An(){return this._isUTC?"Coordinated Universal Time":""}function zn(e){return gt(1e3*e)}function Rn(){return gt.apply(null,arguments).parseZone()}function Wn(e){return e}function Yn(e,t,n,i){var r=tt(),o=c().set(i,t);return r[n](o,e)}function Hn(e,t,n){if("number"==typeof e&&(t=e,e=void 0),e=e||"",null!=t)return Yn(e,t,n,"month");var i,r=[];for(i=0;i<12;i++)r[i]=Yn(e,i,n,"month");return r}function Bn(e,t,n,i){"boolean"==typeof e?("number"==typeof t&&(n=t,t=void 0),t=t||""):(t=e,n=t,e=!1,"number"==typeof t&&(n=t,t=void 0),t=t||"");var r=tt(),o=e?r._week.dow:0;if(null!=n)return Yn(t,(n+o)%7,i,"day");var a,s=[];for(a=0;a<7;a++)s[a]=Yn(t,(a+o)%7,i,"day");return s}function Un(e,t){return Hn(e,t,"months")}function Fn(e,t){return Hn(e,t,"monthsShort")}function Vn(e,t,n){return Bn(e,t,n,"weekdays")}function Qn(e,t,n){return Bn(e,t,n,"weekdaysShort")}function Gn(e,t,n){return Bn(e,t,n,"weekdaysMin")}function Zn(){var e=this._data;return this._milliseconds=Zr(this._milliseconds),this._days=Zr(this._days),this._months=Zr(this._months),e.milliseconds=Zr(e.milliseconds),e.seconds=Zr(e.seconds),e.minutes=Zr(e.minutes),e.hours=Zr(e.hours),e.months=Zr(e.months),e.years=Zr(e.years),this}function Xn(e,t,n,i){var r=Yt(t,n);return e._milliseconds+=i*r._milliseconds,e._days+=i*r._days,e._months+=i*r._months,e._bubble()}function Jn(e,t){return Xn(this,e,t,1)}function Kn(e,t){return Xn(this,e,t,-1)}function qn(e){return e<0?Math.floor(e):Math.ceil(e)}function $n(){var e,t,n,i,r,o=this._milliseconds,a=this._days,s=this._months,l=this._data;return o>=0&&a>=0&&s>=0||o<=0&&a<=0&&s<=0||(o+=864e5*qn(ti(s)+a),a=0,s=0),l.milliseconds=o%1e3,e=b(o/1e3),l.seconds=e%60,t=b(e/60),l.minutes=t%60,n=b(t/60),l.hours=n%24,a+=b(n/24),r=b(ei(a)),s+=r,a-=qn(ti(r)),i=b(s/12),s%=12,l.days=a,l.months=s,l.years=i,this}function ei(e){return 4800*e/146097}function ti(e){return 146097*e/4800}function ni(e){var t,n,i=this._milliseconds;if(e=A(e),"month"===e||"year"===e)return t=this._days+i/864e5,n=this._months+ei(t),"month"===e?n:n/12;switch(t=this._days+Math.round(ti(this._months)),e){case"week":return t/7+i/6048e5;case"day":return t+i/864e5;case"hour":return 24*t+i/36e5;case"minute":return 1440*t+i/6e4;case"second":return 86400*t+i/1e3;case"millisecond":return Math.floor(864e5*t)+i;default:throw new Error("Unknown unit "+e)}}function ii(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*M(this._months/12)}function ri(e){return function(){return this.as(e)}}function oi(e){return e=A(e),this[e+"s"]()}function ai(e){return function(){return this._data[e]}}function si(){return b(this.days()/7)}function li(e,t,n,i,r){return r.relativeTime(t||1,!!n,e,i)}function ui(e,t,n){var i=Yt(e).abs(),r=co(i.as("s")),o=co(i.as("m")),a=co(i.as("h")),s=co(i.as("d")),l=co(i.as("M")),u=co(i.as("y")),c=r<fo.s&&["s",r]||o<=1&&["m"]||o<fo.m&&["mm",o]||a<=1&&["h"]||a<fo.h&&["hh",a]||s<=1&&["d"]||s<fo.d&&["dd",s]||l<=1&&["M"]||l<fo.M&&["MM",l]||u<=1&&["y"]||["yy",u];return c[2]=t,c[3]=+e>0,c[4]=n,li.apply(null,c)}function ci(e){return void 0===e?co:"function"==typeof e&&(co=e,!0)}function di(e,t){return void 0!==fo[e]&&(void 0===t?fo[e]:(fo[e]=t,!0))}function fi(e){var t=this.localeData(),n=ui(this,!e,t);return e&&(n=t.pastFuture(+this,n)),t.postformat(n)}function pi(){var e,t,n,i=po(this._milliseconds)/1e3,r=po(this._days),o=po(this._months);e=b(i/60),t=b(e/60),i%=60,e%=60,n=b(o/12),o%=12;var a=n,s=o,l=r,u=t,c=e,d=i,f=this.asSeconds();return f?(f<0?"-":"")+"P"+(a?a+"Y":"")+(s?s+"M":"")+(l?l+"D":"")+(u||c||d?"T":"")+(u?u+"H":"")+(c?c+"M":"")+(d?d+"S":""):"P0D"}var hi,mi;mi=Array.prototype.some?Array.prototype.some:function(e){for(var t=Object(this),n=t.length>>>0,i=0;i<n;i++)if(i in t&&e.call(this,t[i],i,t))return!0;return!1};var yi=t.momentProperties=[],vi=!1,gi={};t.suppressDeprecationWarnings=!1,t.deprecationHandler=null;var bi;bi=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)l(e,t)&&n.push(t);return n};var Mi,Ti={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},xi={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},Ci="Invalid date",_i="%d",wi=/\d{1,2}/,Si={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Ni={},Ei={},Pi=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,Di=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Ii={},Li={},ji=/\d/,ki=/\d\d/,Oi=/\d{3}/,Ai=/\d{4}/,zi=/[+-]?\d{6}/,Ri=/\d\d?/,Wi=/\d\d\d\d?/,Yi=/\d\d\d\d\d\d?/,Hi=/\d{1,3}/,Bi=/\d{1,4}/,Ui=/[+-]?\d{1,6}/,Fi=/\d+/,Vi=/[+-]?\d+/,Qi=/Z|[+-]\d\d:?\d\d/gi,Gi=/Z|[+-]\d\d(?::?\d\d)?/gi,Zi=/[+-]?\d+(\.\d{1,3})?/,Xi=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Ji={},Ki={},qi=0,$i=1,er=2,tr=3,nr=4,ir=5,rr=6,or=7,ar=8;Mi=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},Q("M",["MM",2],"Mo",function(){return this.month()+1}),Q("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),Q("MMMM",0,0,function(e){return this.localeData().months(this,e)}),O("month","M"),R("month",8),K("M",Ri),K("MM",Ri,ki),K("MMM",function(e,t){return t.monthsShortRegex(e)}),K("MMMM",function(e,t){return t.monthsRegex(e)}),te(["M","MM"],function(e,t){t[$i]=M(e)-1}),te(["MMM","MMMM"],function(e,t,n,i){var r=n._locale.monthsParse(e,i,n._strict);null!=r?t[$i]=r:f(n).invalidMonth=e});var sr=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,lr="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ur="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),cr=Xi,dr=Xi;Q("Y",0,0,function(){var e=this.year();return e<=9999?""+e:"+"+e}),Q(0,["YY",2],0,function(){return this.year()%100}),Q(0,["YYYY",4],0,"year"),Q(0,["YYYYY",5],0,"year"),Q(0,["YYYYYY",6,!0],0,"year"),O("year","y"),R("year",1),K("Y",Vi),K("YY",Ri,ki),K("YYYY",Bi,Ai),K("YYYYY",Ui,zi),K("YYYYYY",Ui,zi),te(["YYYYY","YYYYYY"],qi),te("YYYY",function(e,n){n[qi]=2===e.length?t.parseTwoDigitYear(e):M(e)}),te("YY",function(e,n){n[qi]=t.parseTwoDigitYear(e)}),te("Y",function(e,t){t[qi]=parseInt(e,10)}),t.parseTwoDigitYear=function(e){return M(e)+(M(e)>68?1900:2e3)};var fr=Y("FullYear",!0);Q("w",["ww",2],"wo","week"),Q("W",["WW",2],"Wo","isoWeek"),O("week","w"),O("isoWeek","W"),R("week",5),R("isoWeek",5),K("w",Ri),K("ww",Ri,ki),K("W",Ri),K("WW",Ri,ki),ne(["w","ww","W","WW"],function(e,t,n,i){t[i.substr(0,1)]=M(e)});var pr={dow:0,doy:6};Q("d",0,"do","day"),Q("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),Q("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),Q("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),Q("e",0,0,"weekday"),Q("E",0,0,"isoWeekday"),O("day","d"),O("weekday","e"),O("isoWeekday","E"),R("day",11),R("weekday",11),R("isoWeekday",11),K("d",Ri),K("e",Ri),K("E",Ri),K("dd",function(e,t){return t.weekdaysMinRegex(e)}),K("ddd",function(e,t){return t.weekdaysShortRegex(e)}),K("dddd",function(e,t){return t.weekdaysRegex(e)}),ne(["dd","ddd","dddd"],function(e,t,n,i){var r=n._locale.weekdaysParse(e,i,n._strict);null!=r?t.d=r:f(n).invalidWeekday=e}),ne(["d","e","E"],function(e,t,n,i){t[i]=M(e)});var hr="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),mr="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),yr="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),vr=Xi,gr=Xi,br=Xi;Q("H",["HH",2],0,"hour"),Q("h",["hh",2],0,Ue),Q("k",["kk",2],0,Fe),Q("hmm",0,0,function(){return""+Ue.apply(this)+V(this.minutes(),2)}),Q("hmmss",0,0,function(){return""+Ue.apply(this)+V(this.minutes(),2)+V(this.seconds(),2)}),Q("Hmm",0,0,function(){return""+this.hours()+V(this.minutes(),2)}),Q("Hmmss",0,0,function(){return""+this.hours()+V(this.minutes(),2)+V(this.seconds(),2)}),Ve("a",!0),Ve("A",!1),O("hour","h"),R("hour",13),K("a",Qe),K("A",Qe),K("H",Ri),K("h",Ri),K("HH",Ri,ki),K("hh",Ri,ki),K("hmm",Wi),K("hmmss",Yi),K("Hmm",Wi),K("Hmmss",Yi),te(["H","HH"],tr),te(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),te(["h","hh"],function(e,t,n){t[tr]=M(e),f(n).bigHour=!0}),te("hmm",function(e,t,n){var i=e.length-2;t[tr]=M(e.substr(0,i)),t[nr]=M(e.substr(i)),f(n).bigHour=!0}),te("hmmss",function(e,t,n){var i=e.length-4,r=e.length-2;t[tr]=M(e.substr(0,i)),t[nr]=M(e.substr(i,2)),t[ir]=M(e.substr(r)),f(n).bigHour=!0}),te("Hmm",function(e,t,n){var i=e.length-2;t[tr]=M(e.substr(0,i)),t[nr]=M(e.substr(i))}),te("Hmmss",function(e,t,n){var i=e.length-4,r=e.length-2;t[tr]=M(e.substr(0,i)),t[nr]=M(e.substr(i,2)),t[ir]=M(e.substr(r))});var Mr,Tr=/[ap]\.?m?\.?/i,xr=Y("Hours",!0),Cr={calendar:Ti,longDateFormat:xi,invalidDate:Ci,ordinal:_i,ordinalParse:wi,relativeTime:Si,months:lr,monthsShort:ur,week:pr,weekdays:hr,weekdaysMin:yr,weekdaysShort:mr,meridiemParse:Tr},_r={},wr=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,Sr=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,Nr=/Z|[+-]\d\d(?::?\d\d)?/,Er=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],Pr=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],Dr=/^\/?Date\((\-?\d+)/i;t.createFromInputFallback=C("value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),t.ISO_8601=function(){};var Ir=C("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=gt.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:h()}),Lr=C("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=gt.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:h()}),jr=function(){return Date.now?Date.now():+new Date};wt("Z",":"),wt("ZZ",""),K("Z",Gi),K("ZZ",Gi),te(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=St(Gi,e)});var kr=/([\+\-]|\d\d)/gi;t.updateOffset=function(){};var Or=/^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,Ar=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;Yt.fn=xt.prototype;var zr=Ft(1,"add"),Rr=Ft(-1,"subtract");t.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",t.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var Wr=C("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});Q(0,["gg",2],0,function(){return this.weekYear()%100}),Q(0,["GG",2],0,function(){return this.isoWeekYear()%100}),wn("gggg","weekYear"),wn("ggggg","weekYear"),wn("GGGG","isoWeekYear"),wn("GGGGG","isoWeekYear"),O("weekYear","gg"),O("isoWeekYear","GG"),R("weekYear",1),R("isoWeekYear",1),K("G",Vi),K("g",Vi),K("GG",Ri,ki),K("gg",Ri,ki),K("GGGG",Bi,Ai),K("gggg",Bi,Ai),K("GGGGG",Ui,zi),K("ggggg",Ui,zi),ne(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,i){t[i.substr(0,2)]=M(e)}),ne(["gg","GG"],function(e,n,i,r){n[r]=t.parseTwoDigitYear(e)}),Q("Q",0,"Qo","quarter"),O("quarter","Q"),R("quarter",7),K("Q",ji),te("Q",function(e,t){t[$i]=3*(M(e)-1)}),Q("D",["DD",2],"Do","date"),O("date","D"),R("date",9),K("D",Ri),K("DD",Ri,ki),K("Do",function(e,t){return e?t._ordinalParse:t._ordinalParseLenient}),te(["D","DD"],er),te("Do",function(e,t){t[er]=M(e.match(Ri)[0],10)});var Yr=Y("Date",!0);Q("DDD",["DDDD",3],"DDDo","dayOfYear"),O("dayOfYear","DDD"),R("dayOfYear",4),K("DDD",Hi),K("DDDD",Oi),te(["DDD","DDDD"],function(e,t,n){n._dayOfYear=M(e)}),Q("m",["mm",2],0,"minute"),O("minute","m"),R("minute",14),K("m",Ri),K("mm",Ri,ki),te(["m","mm"],nr);var Hr=Y("Minutes",!1);Q("s",["ss",2],0,"second"),O("second","s"),R("second",15),K("s",Ri),K("ss",Ri,ki),te(["s","ss"],ir);var Br=Y("Seconds",!1);Q("S",0,0,function(){return~~(this.millisecond()/100)}),Q(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Q(0,["SSS",3],0,"millisecond"),Q(0,["SSSS",4],0,function(){return 10*this.millisecond()}),Q(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),Q(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),Q(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),Q(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),Q(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),O("millisecond","ms"),R("millisecond",16),K("S",Hi,ji),K("SS",Hi,ki),K("SSS",Hi,Oi);var Ur;for(Ur="SSSS";Ur.length<=9;Ur+="S")K(Ur,Fi);for(Ur="S";Ur.length<=9;Ur+="S")te(Ur,kn);var Fr=Y("Milliseconds",!1);Q("z",0,0,"zoneAbbr"),Q("zz",0,0,"zoneName");var Vr=v.prototype;Vr.add=zr,Vr.calendar=Gt,Vr.clone=Zt,Vr.diff=tn,Vr.endOf=hn,Vr.format=an,Vr.from=sn,Vr.fromNow=ln,Vr.to=un,Vr.toNow=cn,Vr.get=U,Vr.invalidAt=Cn,Vr.isAfter=Xt,Vr.isBefore=Jt,Vr.isBetween=Kt,Vr.isSame=qt,Vr.isSameOrAfter=$t,Vr.isSameOrBefore=en,Vr.isValid=Tn,Vr.lang=Wr,Vr.locale=dn,Vr.localeData=fn,Vr.max=Lr,Vr.min=Ir,Vr.parsingFlags=xn,Vr.set=F,Vr.startOf=pn,Vr.subtract=Rr,Vr.toArray=gn,Vr.toObject=bn,Vr.toDate=vn,Vr.toISOString=on,Vr.toJSON=Mn,Vr.toString=rn,Vr.unix=yn,Vr.valueOf=mn,Vr.creationData=_n,Vr.year=fr,Vr.isLeapYear=ve,Vr.weekYear=Sn,Vr.isoWeekYear=Nn,Vr.quarter=Vr.quarters=Ln,Vr.month=ce,Vr.daysInMonth=de,Vr.week=Vr.weeks=Ne,Vr.isoWeek=Vr.isoWeeks=Ee,Vr.weeksInYear=Pn,Vr.isoWeeksInYear=En,Vr.date=Yr,Vr.day=Vr.days=Ae,Vr.weekday=ze,Vr.isoWeekday=Re,Vr.dayOfYear=jn,Vr.hour=Vr.hours=xr,Vr.minute=Vr.minutes=Hr,Vr.second=Vr.seconds=Br,Vr.millisecond=Vr.milliseconds=Fr,Vr.utcOffset=Pt,Vr.utc=It,Vr.local=Lt,Vr.parseZone=jt,Vr.hasAlignedHourOffset=kt,Vr.isDST=Ot,Vr.isLocal=zt,Vr.isUtcOffset=Rt,Vr.isUtc=Wt,Vr.isUTC=Wt,Vr.zoneAbbr=On,Vr.zoneName=An,Vr.dates=C("dates accessor is deprecated. Use date instead.",Yr),Vr.months=C("months accessor is deprecated. Use month instead",ce),Vr.years=C("years accessor is deprecated. Use year instead",fr),Vr.zone=C("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",Dt),Vr.isDSTShifted=C("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",At);var Qr=Vr,Gr=E.prototype;Gr.calendar=P,Gr.longDateFormat=D,Gr.invalidDate=I,Gr.ordinal=L,Gr.preparse=Wn,Gr.postformat=Wn,Gr.relativeTime=j,Gr.pastFuture=k,Gr.set=S,Gr.months=oe,Gr.monthsShort=ae,Gr.monthsParse=le,Gr.monthsRegex=pe,Gr.monthsShortRegex=fe,Gr.week=_e,Gr.firstDayOfYear=Se,Gr.firstDayOfWeek=we,Gr.weekdays=Ie,Gr.weekdaysMin=je,Gr.weekdaysShort=Le,Gr.weekdaysParse=Oe,Gr.weekdaysRegex=We,Gr.weekdaysShortRegex=Ye,Gr.weekdaysMinRegex=He,Gr.isPM=Ge,Gr.meridiem=Ze,qe("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10,n=1===M(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th";return e+n}}),t.lang=C("moment.lang is deprecated. Use moment.locale instead.",qe),t.langData=C("moment.langData is deprecated. Use moment.localeData instead.",tt);var Zr=Math.abs,Xr=ri("ms"),Jr=ri("s"),Kr=ri("m"),qr=ri("h"),$r=ri("d"),eo=ri("w"),to=ri("M"),no=ri("y"),io=ai("milliseconds"),ro=ai("seconds"),oo=ai("minutes"),ao=ai("hours"),so=ai("days"),lo=ai("months"),uo=ai("years"),co=Math.round,fo={s:45,m:45,h:22,d:26,M:11},po=Math.abs,ho=xt.prototype;ho.abs=Zn,ho.add=Jn,ho.subtract=Kn,ho.as=ni,ho.asMilliseconds=Xr,ho.asSeconds=Jr,ho.asMinutes=Kr,ho.asHours=qr,ho.asDays=$r,ho.asWeeks=eo,ho.asMonths=to,ho.asYears=no,ho.valueOf=ii,ho._bubble=$n,ho.get=oi,ho.milliseconds=io,ho.seconds=ro,ho.minutes=oo,ho.hours=ao,ho.days=so,ho.weeks=si,ho.months=lo,ho.years=uo,ho.humanize=fi,ho.toISOString=pi,ho.toString=pi,ho.toJSON=pi,ho.locale=dn,ho.localeData=fn,ho.toIsoString=C("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",pi),ho.lang=Wr,Q("X",0,0,"unix"),Q("x",0,0,"valueOf"),K("x",Vi),K("X",Zi),te("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e,10))}),te("x",function(e,t,n){n._d=new Date(M(e))}),t.version="2.15.2",n(gt),t.fn=Qr,t.min=Mt,t.max=Tt,t.now=jr,t.utc=c,t.unix=zn,t.months=Un,t.isDate=a,t.locale=qe,t.invalid=h,t.duration=Yt,t.isMoment=g,t.weekdays=Vn,t.parseZone=Rn,t.localeData=tt,t.isDuration=Ct,t.monthsShort=Fn,t.weekdaysMin=Gn,t.defineLocale=$e,t.updateLocale=et,t.locales=nt,t.weekdaysShort=Qn,t.normalizeUnits=A,t.relativeTimeRounding=ci,t.relativeTimeThreshold=di,t.calendarFormat=Qt,t.prototype=Qr;var mo=t;return mo})},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={isAppearSupported:function(e){return e.transitionName&&e.transitionAppear||e.animation.appear},isEnterSupported:function(e){return e.transitionName&&e.transitionEnter||e.animation.enter},isLeaveSupported:function(e){return e.transitionName&&e.transitionLeave||e.animation.leave},allowAppearCallback:function(e){return e.transitionAppear||e.animation.appear},allowEnterCallback:function(e){return e.transitionEnter||e.animation.enter},allowLeaveCallback:function(e){return e.transitionLeave||e.animation.leave}};t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(348)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(39),s=i(a),l=o["default"].createClass({displayName:"ExpandIcon",propTypes:{record:r.PropTypes.object,prefixCls:r.PropTypes.string,expandable:r.PropTypes.any,expanded:r.PropTypes.bool,needIndentSpaced:r.PropTypes.bool,onExpand:r.PropTypes.func},shouldComponentUpdate:function(e){return!(0,s["default"])(e,this.props)},render:function(){var e=this.props,t=e.expandable,n=e.prefixCls,i=e.onExpand,r=e.needIndentSpaced,a=e.expanded,s=e.record;if(t){var l=a?"expanded":"collapsed";return o["default"].createElement("span",{className:n+"-expand-icon "+n+"-"+l,onClick:function(e){return i(!a,s,e)}})}return r?o["default"].createElement("span",{className:n+"-expand-icon "+n+"-spaced"}):null}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(6),o=i(r),a=n(7),s=i(a),l=n(1),u=i(l),c=n(5),d=i(c),f={"float":"right"};t["default"]={getDefaultProps:function(){return{styles:{}}},onTabClick:function(e){this.props.onTabClick(e)},getTabs:function(){var e=this,t=this.props,n=t.panels,i=t.activeKey,r=[],o=t.prefixCls;return u["default"].Children.forEach(n,function(t){if(t){var n=t.key,a=i===n?o+"-tab-active":"";a+=" "+o+"-tab";var l={};t.props.disabled?a+=" "+o+"-tab-disabled":l={onClick:e.onTabClick.bind(e,n)};var c={};i===n&&(c.ref="activeTab"),r.push(u["default"].createElement("div",(0,s["default"])({role:"tab","aria-disabled":t.props.disabled?"true":"false","aria-selected":i===n?"true":"false"},l,{className:a,key:n},c),t.props.tab))}}),r},getRootNode:function(e){var t,n=this.props,i=n.prefixCls,r=n.onKeyDown,a=n.className,s=n.extraContent,l=n.style,c=(0, d["default"])((t={},(0,o["default"])(t,i+"-bar",1),(0,o["default"])(t,a,!!a),t));return u["default"].createElement("div",{role:"tablist",className:c,tabIndex:"0",ref:"root",onKeyDown:r,style:l},s?u["default"].createElement("div",{style:f,key:"extra"},s):null,e)}},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(6),o=i(r),a=n(1),s=i(a),l=n(5),u=i(l),c=s["default"].createClass({displayName:"TabPane",propTypes:{className:a.PropTypes.string,active:a.PropTypes.bool,style:a.PropTypes.any,destroyInactiveTabPane:a.PropTypes.bool,forceRender:a.PropTypes.bool,placeholder:a.PropTypes.node},getDefaultProps:function(){return{placeholder:null}},render:function(){var e,t=this.props,n=t.className,i=t.destroyInactiveTabPane,r=t.active,a=t.forceRender;this._isActived=this._isActived||r;var l=t.rootPrefixCls+"-tabpane",c=(0,u["default"])((e={},(0,o["default"])(e,l,1),(0,o["default"])(e,l+"-inactive",!r),(0,o["default"])(e,l+"-active",r),(0,o["default"])(e,n,n),e)),d=i?r:this._isActived;return s["default"].createElement("div",{style:t.style,role:"tabpanel","aria-hidden":t.active?"false":"true",className:c},d||a?t.children:t.placeholder)}});t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.TabPane=t["default"]=void 0;var r=n(393),o=i(r),a=n(111),s=i(a);t["default"]=o["default"],t.TabPane=s["default"]},function(e,t,n){"use strict";e.exports=n(394)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(52),o=i(r),a=n(1),s=i(a),l=s["default"].createClass({displayName:"LazyRenderBox",propTypes:{children:a.PropTypes.any,className:a.PropTypes.string,visible:a.PropTypes.bool,hiddenClassName:a.PropTypes.string},shouldComponentUpdate:function(e){return e.hiddenClassName||e.visible},render:function(){var e=this.props,t=e.hiddenClassName,n=e.visible,i=(0,o["default"])(e,["hiddenClassName","visible"]);return t||s["default"].Children.count(i.children)>1?(!n&&t&&(i.className+=" "+t),s["default"].createElement("div",i)):s["default"].Children.only(i.children)}});t["default"]=l,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var i=function r(e){n(this,r);var t=[];e=e||{},this.subscribe=function(e){t.push(e)},this.unsubscribe=function(e){var n=t.indexOf(e);n!==-1&&t.splice(n,1)},this.update=function(n){n&&n(e),t.forEach(function(t){return t(e)})}};t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(52),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(9),v=i(y),g=n(419),b=i(g),M=n(423),T=i(M),x=n(422),C=i(x),_=n(424),w=i(_),S=n(409),N=i(S),E=n(10),P=i(E),D=n(405),I=i(D),L=n(124),j=i(L),k=n(407),O=n(73),A=n(420),z=i(A),R=1,W=10,Y=1e3,H=1e3,B=50,U="listviewscroll",F=function(e){function t(){var n,i,r;(0,u["default"])(this,t);for(var o=arguments.length,a=Array(o),s=0;s<o;s++)a[s]=arguments[s];return n=i=(0,d["default"])(this,e.call.apply(e,[this].concat(a))),i.state={curRenderedRowsCount:i.props.initialListSize,highlightedRow:{}},i.stickyRefs={},r=n,(0,d["default"])(i,r)}return(0,p["default"])(t,e),t.prototype.getMetrics=function(){return{contentLength:this.scrollProperties.contentLength,totalRows:this.props.dataSource.getRowCount(),renderedRows:this.state.curRenderedRowsCount,visibleRows:Object.keys(this._visibleRows).length}},t.prototype.getScrollResponder=function(){return this.refs[U]&&this.refs[U].getScrollResponder&&this.refs[U].getScrollResponder()},t.prototype.scrollTo=function(){var e;this.refs[U]&&this.refs[U].scrollTo&&(e=this.refs[U]).scrollTo.apply(e,arguments)},t.prototype.setNativeProps=function(e){this.refs[U]&&this.refs[U].setNativeProps(e)},t.prototype.getInnerViewNode=function(){return this.refs[U].getInnerViewNode()},t.prototype.componentWillMount=function(){this.scrollProperties={visibleLength:null,contentLength:null,offset:0},this._childFrames=[],this._visibleRows={},this._prevRenderedRowsCount=0,this._sentEndForContentLength=null},t.prototype.componentDidMount=function(){(this.props.stickyHeader||this.props.useBodyScroll)&&(this.__onScroll=(0,O.throttle)(this._onScroll,this.props.scrollEventThrottle),window.addEventListener("scroll",this.__onScroll))},t.prototype.componentWillReceiveProps=function(e){var t=this;this.props.dataSource===e.dataSource&&this.props.initialListSize===e.initialListSize||this.setState(function(e,n){return t._prevRenderedRowsCount=0,{curRenderedRowsCount:Math.min(Math.max(e.curRenderedRowsCount,n.initialListSize),n.dataSource.getRowCount())}},function(){return t._renderMoreRowsIfNeeded()})},t.prototype.componentWillUnmount=function(){(this.props.stickyHeader||this.props.useBodyScroll)&&window.removeEventListener("scroll",this.__onScroll)},t.prototype.onRowHighlighted=function(e,t){this.setState({highlightedRow:{sectionID:e,rowID:t}})},t.prototype.render=function(){var e=this,t=[],n=this.props.dataSource,i=n.rowIdentities,r=0,a=[],l=this.props.renderHeader&&this.props.renderHeader(),u=this.props.renderFooter&&this.props.renderFooter(),c=l?1:0,d=function(s){var l=n.sectionIdentities[s],u=i[s];if(0===u.length)return"continue";if(e.props.renderSectionHeader){var d=r>=e._prevRenderedRowsCount&&n.sectionHeaderShouldUpdate(s),f=m["default"].createElement(w["default"],{key:"s_"+l,shouldUpdate:!!d,render:e.props.renderSectionHeader.bind(null,n.getSectionHeaderData(s),l)});e.props.stickyHeader&&(f=m["default"].createElement(k.Sticky,(0,o["default"])({},e.props.stickyProps,{key:"s_"+l,ref:function(t){e.stickyRefs[l]=t}}),f)),t.push(f),a.push(c++)}for(var p=[],h=0;h<u.length;h++){var y=u[h],v=l+"_"+y,g=r>=e._prevRenderedRowsCount&&n.rowShouldUpdate(s,h),b=m["default"].createElement(w["default"],{key:"r_"+v,shouldUpdate:!!g,render:e.props.renderRow.bind(null,n.getRowData(s,h),l,y,e.onRowHighlighted)});if(p.push(b),c++,e.props.renderSeparator&&(h!==u.length-1||s===i.length-1)){var M=e.state.highlightedRow.sectionID===l&&(e.state.highlightedRow.rowID===y||e.state.highlightedRow.rowID===u[h+1]),T=e.props.renderSeparator(l,y,M);T&&(p.push(T),c++)}if(++r===e.state.curRenderedRowsCount)break}return t.push(m["default"].cloneElement(e.props.renderSectionBodyWrapper(l),{className:e.props.sectionBodyClassName},p)),r>=e.state.curRenderedRowsCount?"break":void 0};e:for(var f=0;f<i.length;f++){var p=d(f);switch(p){case"continue":continue;case"break":break e}}var h=this.props,y=h.renderScrollComponent,v=(0,s["default"])(h,["renderScrollComponent"]);return t=m["default"].cloneElement(v.renderBodyComponent(),{},t),v.stickyHeader&&(t=m["default"].createElement(k.StickyContainer,v.stickyContainerProps,t)),(0,P["default"])(v,{onScroll:this._onScroll}),(v.stickyHeader||v.useBodyScroll)&&delete v.onScroll,this._sc=m["default"].cloneElement(y(v),{ref:U,onContentSizeChange:this._onContentSizeChange,onLayout:v.stickyHeader||v.useBodyScroll?function(t){e.props.onLayout&&e.props.onLayout(t)}:this._onLayout},l,t,u,v.children),this._sc},t.prototype._measureAndUpdateScrollProps=function(){var e=this.getScrollResponder();!e||!e.getInnerViewNode},t.prototype._onContentSizeChange=function(e,t){var n=this.props.horizontal?e:t;n!==this.scrollProperties.contentLength&&(this.scrollProperties.contentLength=n,this._updateVisibleRows(),this._renderMoreRowsIfNeeded()),this.props.onContentSizeChange&&this.props.onContentSizeChange(e,t)},t.prototype._onLayout=function(e){var t=e.nativeEvent.layout,n=t.width,i=t.height,r=this.props.horizontal?n:i;r!==this.scrollProperties.visibleLength&&(this.scrollProperties.visibleLength=r,this._updateVisibleRows(),this._renderMoreRowsIfNeeded()),this.props.onLayout&&this.props.onLayout(e)},t.prototype._maybeCallOnEndReached=function(e){return!!(this.props.onEndReached&&this._getDistanceFromEnd(this.scrollProperties)<this.props.onEndReachedThreshold&&this.state.curRenderedRowsCount===this.props.dataSource.getRowCount())&&(this._sentEndForContentLength=this.scrollProperties.contentLength,this.props.onEndReached(e),!0)},t.prototype._renderMoreRowsIfNeeded=function(){if(null===this.scrollProperties.contentLength||null===this.scrollProperties.visibleLength||this.state.curRenderedRowsCount===this.props.dataSource.getRowCount())return void this._maybeCallOnEndReached();var e=this._getDistanceFromEnd(this.scrollProperties);e<this.props.scrollRenderAheadDistance&&this._pageInNewRows()},t.prototype._pageInNewRows=function(){var e=this;this.setState(function(t,n){var i=Math.min(t.curRenderedRowsCount+n.pageSize,n.dataSource.getRowCount());return e._prevRenderedRowsCount=t.curRenderedRowsCount,{curRenderedRowsCount:i}},function(){e._measureAndUpdateScrollProps(),e._prevRenderedRowsCount=e.state.curRenderedRowsCount})},t.prototype._getDistanceFromEnd=function(e){return e.contentLength-e.visibleLength-e.offset},t.prototype._updateVisibleRows=function(e){},t.prototype._onScroll=function(e){var t=!this.props.horizontal,n=e,i=v["default"].findDOMNode(this.refs[U]);if(this.props.stickyHeader||this.props.useBodyScroll)this.scrollProperties.visibleLength=window[t?"innerHeight":"innerWidth"],this.scrollProperties.contentLength=i[t?"scrollHeight":"scrollWidth"],this.scrollProperties.offset=window.document.body[t?"scrollTop":"scrollLeft"];else if(this.props.useZscroller){var r=this.refs[U].domScroller;n=r,this.scrollProperties.visibleLength=r.container[t?"clientHeight":"clientWidth"],this.scrollProperties.contentLength=r.content[t?"offsetHeight":"offsetWidth"],this.scrollProperties.offset=r.scroller.getValues()[t?"top":"left"]}else this.scrollProperties.visibleLength=i[t?"offsetHeight":"offsetWidth"],this.scrollProperties.contentLength=i[t?"scrollHeight":"scrollWidth"],this.scrollProperties.offset=i[t?"scrollTop":"scrollLeft"];this._maybeCallOnEndReached(n)||this._renderMoreRowsIfNeeded(),this.props.onEndReached&&this._getDistanceFromEnd(this.scrollProperties)>this.props.onEndReachedThreshold&&(this._sentEndForContentLength=null),this.props.onScroll&&this.props.onScroll(n)},t}(m["default"].Component);F.DataSource=b["default"],F.propTypes=(0,o["default"])({},T["default"].propTypes,{dataSource:h.PropTypes.instanceOf(b["default"]).isRequired,renderSeparator:h.PropTypes.func,renderRow:h.PropTypes.func.isRequired,initialListSize:h.PropTypes.number,onEndReached:h.PropTypes.func,onEndReachedThreshold:h.PropTypes.number,pageSize:h.PropTypes.number,renderFooter:h.PropTypes.func,renderHeader:h.PropTypes.func,renderSectionHeader:h.PropTypes.func,renderScrollComponent:m["default"].PropTypes.func.isRequired,scrollRenderAheadDistance:m["default"].PropTypes.number,onChangeVisibleRows:m["default"].PropTypes.func,scrollEventThrottle:m["default"].PropTypes.number,renderBodyComponent:h.PropTypes.func,renderSectionBodyWrapper:h.PropTypes.func,sectionBodyClassName:h.PropTypes.string,useZscroller:h.PropTypes.bool,useBodyScroll:h.PropTypes.bool,stickyHeader:h.PropTypes.bool,stickyProps:h.PropTypes.object,stickyContainerProps:h.PropTypes.object}),F.defaultProps={initialListSize:W,pageSize:R,renderScrollComponent:function(e){return m["default"].createElement(T["default"],e)},renderBodyComponent:function(){return m["default"].createElement("div",null)},renderSectionBodyWrapper:function(e){return m["default"].createElement("div",{key:e})},sectionBodyClassName:"list-view-section-body",scrollRenderAheadDistance:Y,onEndReachedThreshold:H,scrollEventThrottle:B,stickyProps:{},stickyContainerProps:{}},(0,I["default"])(F.prototype,C["default"].Mixin),(0,I["default"])(F.prototype,N["default"]),(0,I["default"])(F.prototype,z["default"]),(0,j["default"])(F),F.isReactNativeComponent=!0,t["default"]=F,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),s=n(1),l=i(s),u=n(5),c=r(u),d=n(427),f=r(d),p=n(119),h=r(p),m=l.createClass({displayName:"Picker",getDefaultProps:function(){return{prefixCls:"rmc-picker",pure:!0,onValueChange:function(){}}},getInitialState:function(){var e=void 0,t=this.props,n=t.selectedValue,i=t.defaultSelectedValue,r=t.children;return void 0!==n?e=n:void 0!==i?e=i:r.length&&(e=r[0].value),{selectedValue:e}},componentDidMount:function(){this.itemHeight=this.refs.indicator.offsetHeight,this.refs.content.style.padding=3*this.itemHeight+"px 0",this.zscroller=new h["default"](this.refs.content,{scrollingX:!1,snapping:!0,penetrationDeceleration:.1,minVelocityToKeepDecelerating:.5,scrollingComplete:this.scrollingComplete}),this.zscroller.setDisabled(this.props.disabled),this.zscroller.scroller.setSnapSize(0,this.itemHeight),this.select(this.state.selectedValue)},componentWillReceiveProps:function(e){"selectedValue"in e&&this.setState({selectedValue:e.selectedValue}),this.zscroller.setDisabled(e.disabled)},shouldComponentUpdate:function(e,t){return this.state.selectedValue!==t.selectedValue||!(0,f["default"])(this.props.children,e.children,this.props.pure)},componentDidUpdate:function(){this.zscroller.reflow(),this.select(this.state.selectedValue)},componentWillUnmount:function(){this.zscroller.destroy()},selectByIndex:function(e){e<0||e>=this.props.children.length||this.zscroller.scroller.scrollTo(0,e*this.itemHeight)},select:function(e){for(var t=this.props.children,n=0,i=t.length;n<i;n++)if(t[n].value===e)return void this.selectByIndex(n);this.selectByIndex(0)},fireValueChange:function(e){e!==this.state.selectedValue&&("selectedValue"in this.props||this.setState({selectedValue:e}),this.props.onValueChange(e))},scrollingComplete:function(){var e=this.zscroller.scroller.getValues(),t=e.top,n=Math.round((t-this.itemHeight/2)/this.itemHeight),i=this.props.children[n];i&&this.fireValueChange(i.value)},render:function(){var e,t=this.props,n=t.children,i=t.prefixCls,r=t.className,o=t.itemStyle,s=this.state.selectedValue,u=i+"-item",d=u+" "+i+"-item-selected",f=n.map(function(e){return l.createElement("div",{style:o,className:s===e.value?d:u,key:e.value},e.label)}),p=(e={},(0,a["default"])(e,r,!!r),(0,a["default"])(e,i,!0),e);return l.createElement("div",{className:(0,c["default"])(p)},l.createElement("div",{className:i+"-mask"}),l.createElement("div",{className:i+"-indicator",ref:"indicator"}),l.createElement("div",{className:i+"-content",ref:"content"},f))}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),s=n(46),l=i(s),u=n(425),c=i(u),d=a.createClass({displayName:"PopupPicker",mixins:[c["default"]],getDefaultProps:function(){return{prefixCls:"rmc-picker-popup",triggerType:"onClick",WrapComponent:"span"}},getModal:function(){var e=this.props;return this.state.visible?a.createElement(l["default"],{prefixCls:""+e.prefixCls,className:e.className||"",visible:!0,closable:!1,transitionName:e.transitionName||e.popupTransitionName,maskTransitionName:e.maskTransitionName,onClose:this.hide,style:e.style},a.createElement("div",null,a.createElement("div",{className:e.prefixCls+"-header"},a.createElement("div",{className:e.prefixCls+"-item "+e.prefixCls+"-header-left",onClick:this.onDismiss},e.dismissText),a.createElement("div",{className:e.prefixCls+"-item "+e.prefixCls+"-title"},e.title),a.createElement("div",{className:e.prefixCls+"-item "+e.prefixCls+"-header-right",onClick:this.onOk},e.okText)),this.props.content)):null},render:function(){return this.getRender()}});t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function i(e,t){e.transform=t,e.webkitTransform=t,e.MozTransform=t}function r(e,t){e.transformOrigin=t,e.webkitTransformOrigin=t,e.MozTransformOrigin=t}function o(e){var t=this,n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],o=void 0,u=void 0,c=void 0,d=void 0,f=void 0,p=void 0,h=void 0,m=void 0;this.content=e,this.container=e.parentNode,this.options=a({},n,{scrollingComplete:function(){t.clearScrollbarTimer(),t.timer=setTimeout(function(){n.scrollingComplete&&n.scrollingComplete(),o&&["x","y"].forEach(function(e){o[e]&&t.setScrollbarOpacity(e,0)})},0)}}),this.options.scrollbars&&(o=this.scrollbars={},u=this.indicators={},c=this.indicatorsSize={},d=this.scrollbarsSize={},f=this.indicatorsPos={},p=this.scrollbarsOpacity={},h=this.contentSize={},m=this.clientSize={},["x","y"].forEach(function(e){var n="x"===e?"scrollingX":"scrollingY";t.options[n]!==!1&&(o[e]=document.createElement("div"),o[e].className="zscroller-scrollbar-"+e,u[e]=document.createElement("div"),u[e].className="zscroller-indicator-"+e,o[e].appendChild(u[e]),c[e]=-1,p[e]=0,f[e]=0,t.container.appendChild(o[e]))}));var y=!0,v=e.style;this.scroller=new s(function(e,r,a){!y&&n.onScroll&&n.onScroll(),i(v,"translate3d("+-e+"px,"+-r+"px,0) scale("+a+")"),o&&["x","y"].forEach(function(n){if(o[n]){var i="x"===n?e:r;if(m[n]>=h[n])t.setScrollbarOpacity(n,0);else{y||t.setScrollbarOpacity(n,1);var a=m[n]/h[n]*d[n],s=a,u=void 0;i<0?(s=Math.max(a+i,l),u=0):i>h[n]-m[n]?(s=Math.max(a+h[n]-m[n]-i,l),u=d[n]-s):u=i/h[n]*d[n],t.setIndicatorSize(n,s),t.setIndicatorPos(n,u)}}}),y=!1},this.options),this.bindEvents(),r(e.style,"left top"),this.reflow()}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},s=n(450),l=8;o.prototype.setDisabled=function(e){this.disabled=e},o.prototype.clearScrollbarTimer=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},o.prototype.setScrollbarOpacity=function(e,t){this.scrollbarsOpacity[e]!==t&&(this.scrollbars[e].style.opacity=t,this.scrollbarsOpacity[e]=t)},o.prototype.setIndicatorPos=function(e,t){this.indicatorsPos[e]!==t&&("x"===e?i(this.indicators[e].style,"translate3d("+t+"px,0,0)"):i(this.indicators[e].style,"translate3d(0, "+t+"px,0)"),this.indicatorsPos[e]=t)},o.prototype.setIndicatorSize=function(e,t){this.indicatorsSize[e]!==t&&(this.indicators[e].style["x"===e?"width":"height"]=t+"px",this.indicatorsSize[e]=t)},o.prototype.reflow=function(){this.scrollbars&&(this.contentSize.x=this.content.offsetWidth,this.contentSize.y=this.content.offsetHeight,this.clientSize.x=this.container.clientWidth,this.clientSize.y=this.container.clientHeight,this.scrollbars.x&&(this.scrollbarsSize.x=this.scrollbars.x.offsetWidth),this.scrollbars.y&&(this.scrollbarsSize.y=this.scrollbars.y.offsetHeight)),this.scroller.setDimensions(this.container.clientWidth,this.container.clientHeight,this.content.offsetWidth,this.content.offsetHeight);var e=this.container.getBoundingClientRect();this.scroller.setPosition(e.x+this.container.clientLeft,e.y+this.container.clientTop)},o.prototype.destroy=function(){window.removeEventListener("resize",this.onResize,!1),this.container.removeEventListener("touchstart",this.onTouchStart,!1),this.container.removeEventListener("touchmove",this.onTouchMove,!1),this.container.removeEventListener("touchend",this.onTouchEnd,!1),this.container.removeEventListener("touchcancel",this.onTouchCancel,!1),this.container.removeEventListener("mousedown",this.onMouseDown,!1),document.removeEventListener("mousemove",this.onMouseMove,!1),document.removeEventListener("mouseup",this.onMouseUp,!1),this.container.removeEventListener("mousewheel",this.onMouseWheel,!1)},o.prototype.bindEvents=function(){var e=this,t=this;window.addEventListener("resize",this.onResize=function(){t.reflow()},!1),"ontouchstart"in window?(this.container.addEventListener("touchstart",this.onTouchStart=function(n){n.touches[0]&&n.touches[0].target&&n.touches[0].target.tagName.match(/input|textarea|select/i)||e.disabled||(e.clearScrollbarTimer(),t.reflow(),t.scroller.doTouchStart(n.touches,n.timeStamp))},!1),this.container.addEventListener("touchmove",this.onTouchMove=function(e){e.preventDefault(),t.scroller.doTouchMove(e.touches,e.timeStamp,e.scale)},!1),this.container.addEventListener("touchend",this.onTouchEnd=function(e){t.scroller.doTouchEnd(e.timeStamp)},!1),this.container.addEventListener("touchcancel",this.onTouchCancel=function(e){t.scroller.doTouchEnd(e.timeStamp)},!1)):!function(){var n=!1;e.container.addEventListener("mousedown",e.onMouseDown=function(i){i.target.tagName.match(/input|textarea|select/i)||e.disabled||(e.clearScrollbarTimer(),t.scroller.doTouchStart([{pageX:i.pageX,pageY:i.pageY}],i.timeStamp),n=!0,t.reflow(),i.preventDefault())},!1),document.addEventListener("mousemove",e.onMouseMove=function(e){n&&(t.scroller.doTouchMove([{pageX:e.pageX,pageY:e.pageY}],e.timeStamp),n=!0)},!1),document.addEventListener("mouseup",e.onMouseUp=function(e){n&&(t.scroller.doTouchEnd(e.timeStamp),n=!1)},!1),e.container.addEventListener("mousewheel",e.onMouseWheel=function(e){t.options.zooming&&(t.scroller.doMouseZoom(e.wheelDelta,e.timeStamp,e.pageX,e.pageY),e.preventDefault())},!1)}()},e.exports=o},function(e,t,n){function i(e){return n(r(e))}function r(e){return o[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var o={"./accordion/index.web.tsx":126,"./accordion/style/index.web.tsx":127,"./action-sheet/index.web.tsx":129,"./action-sheet/style/index.web.tsx":130,"./activity-indicator/index.web.tsx":131,"./activity-indicator/style/index.web.tsx":132,"./badge/index.web.tsx":75,"./badge/style/index.web.tsx":76,"./button/index.web.tsx":47,"./button/style/index.web.tsx":48,"./card/index.web.tsx":136,"./card/style/index.web.tsx":137,"./carousel/index.web.tsx":77,"./carousel/style/index.web.tsx":78,"./checkbox/index.web.tsx":140,"./checkbox/style/index.web.tsx":79,"./date-picker/index.web.tsx":141,"./date-picker/style/index.web.tsx":143,"./drawer/index.web.tsx":145,"./drawer/style/index.web.tsx":146,"./flex/index.web.tsx":32,"./flex/style/index.web.tsx":33,"./grid/index.web.tsx":149,"./grid/style/index.web.tsx":150,"./icon/index.web.tsx":13,"./icon/style/index.web.tsx":16,"./image-picker/index.web.tsx":151,"./image-picker/style/index.web.tsx":152,"./input-item/index.web.tsx":153,"./input-item/style/index.web.tsx":154,"./list-view/index.web.tsx":156,"./list-view/style/index.web.tsx":157,"./list/index.web.tsx":26,"./list/style/index.web.tsx":20,"./menu/index.web.tsx":160,"./menu/style/index.web.tsx":161,"./modal/index.web.tsx":81,"./modal/style/index.web.tsx":82,"./nav-bar/index.web.tsx":165,"./nav-bar/style/index.web.tsx":166,"./notice-bar/index.web.tsx":167,"./notice-bar/style/index.web.tsx":168,"./pagination/index.web.tsx":169,"./pagination/style/index.web.tsx":170,"./picker/index.web.tsx":171,"./picker/style/index.web.tsx":83,"./popover/index.web.tsx":172,"./popover/style/index.web.tsx":174,"./popup/index.web.tsx":175,"./popup/style/index.web.tsx":176,"./progress/index.web.tsx":177,"./progress/style/index.web.tsx":178,"./radio/index.web.tsx":180,"./radio/style/index.web.tsx":84,"./refresh-control/index.web.tsx":181,"./refresh-control/style/index.web.tsx":182,"./result/index.web.tsx":183,"./result/style/index.web.tsx":184,"./search-bar/index.web.tsx":186,"./search-bar/style/index.web.tsx":187,"./segmented-control/index.web.tsx":189,"./segmented-control/style/index.web.tsx":190,"./slider/index.web.tsx":191,"./slider/style/index.web.tsx":192,"./stepper/index.web.tsx":193,"./stepper/style/index.web.tsx":194,"./steps/index.web.tsx":195,"./steps/style/index.web.tsx":196,"./style/index.web.tsx":8,"./swipe-action/index.web.tsx":197,"./swipe-action/style/index.web.tsx":198,"./switch/index.web.tsx":199,"./switch/style/index.web.tsx":200,"./tab-bar/index.web.tsx":202,"./tab-bar/style/index.web.tsx":203,"./table/index.web.tsx":204,"./table/style/index.web.tsx":205,"./tabs/index.web.tsx":206,"./tabs/style/index.web.tsx":207,"./tag/index.web.tsx":208,"./tag/style/index.web.tsx":209,"./text/index.web.tsx":210,"./textarea-item/index.web.tsx":211,"./textarea-item/style/index.web.tsx":212,"./toast/index.web.tsx":85,"./toast/style/index.web.tsx":86,"./view/index.web.tsx":87,"./white-space/index.web.tsx":213,"./white-space/style/index.web.tsx":214,"./wing-blank/index.web.tsx":88,"./wing-blank/style/index.web.tsx":89};i.keys=function(){return Object.keys(o)},i.resolve=r,e.exports=i,i.id=120},function(e,t,n){function i(e){return n(r(e))}function r(e){return o[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var o={"./check-circle-o.svg":429,"./check-circle.svg":430,"./check.svg":431,"./cross-circle-o.svg":432,"./cross-circle.svg":433,"./cross.svg":434,"./down.svg":435,"./ellipsis-circle.svg":436,"./ellipsis.svg":437,"./exclamation-circle.svg":438,"./info-circle.svg":439,"./koubei-o.svg":440,"./koubei.svg":441,"./left.svg":442,"./loading-o.svg":443,"./loading.svg":444,"./question-circle.svg":445,"./right.svg":446,"./search.svg":447};i.keys=function(){return Object.keys(o)},i.resolve=r,e.exports=i,i.id=121},function(e,t){"use strict";function n(){return!1}function i(){return!0}function r(){this.timeStamp=Date.now(),this.target=void 0,this.currentTarget=void 0}Object.defineProperty(t,"__esModule",{value:!0}),r.prototype={isEventObject:1,constructor:r,isDefaultPrevented:n,isPropagationStopped:n,isImmediatePropagationStopped:n,preventDefault:function(){this.isDefaultPrevented=i},stopPropagation:function(){this.isPropagationStopped=i},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=i,this.stopPropagation()},halt:function(e){e?this.stopImmediatePropagation():this.stopPropagation(),this.preventDefault()}},t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){return null===e||void 0===e}function o(){return f}function a(){return p}function s(e){var t=e.type,n="function"==typeof e.stopPropagation||"boolean"==typeof e.cancelBubble;u["default"].call(this),this.nativeEvent=e;var i=a;"defaultPrevented"in e?i=e.defaultPrevented?o:a:"getPreventDefault"in e?i=e.getPreventDefault()?o:a:"returnValue"in e&&(i=e.returnValue===p?o:a),this.isDefaultPrevented=i;var r=[],s=void 0,l=void 0,c=void 0,d=h.concat();for(m.forEach(function(e){t.match(e.reg)&&(d=d.concat(e.props),e.fix&&r.push(e.fix))}),l=d.length;l;)c=d[--l],this[c]=e[c];for(!this.target&&n&&(this.target=e.srcElement||document),this.target&&3===this.target.nodeType&&(this.target=this.target.parentNode),l=r.length;l;)(s=r[--l])(this,e);this.timeStamp=e.timeStamp||Date.now()}Object.defineProperty(t,"__esModule",{value:!0});var l=n(122),u=i(l),c=n(10),d=i(c),f=!0,p=!1,h=["altKey","bubbles","cancelable","ctrlKey","currentTarget","eventPhase","metaKey","shiftKey","target","timeStamp","view","type"],m=[{reg:/^key/,props:["char","charCode","key","keyCode","which"],fix:function(e,t){r(e.which)&&(e.which=r(t.charCode)?t.keyCode:t.charCode),void 0===e.metaKey&&(e.metaKey=e.ctrlKey)}},{reg:/^touch/,props:["touches","changedTouches","targetTouches"]},{reg:/^hashchange$/,props:["newURL","oldURL"]},{reg:/^gesturechange$/i,props:["rotation","scale"]},{reg:/^(mousewheel|DOMMouseScroll)$/,props:[],fix:function(e,t){var n=void 0,i=void 0,r=void 0,o=t.wheelDelta,a=t.axis,s=t.wheelDeltaY,l=t.wheelDeltaX,u=t.detail;o&&(r=o/120),u&&(r=0-(u%3===0?u/3:u)),void 0!==a&&(a===e.HORIZONTAL_AXIS?(i=0,n=0-r):a===e.VERTICAL_AXIS&&(n=0,i=r)),void 0!==s&&(i=s/120),void 0!==l&&(n=-1*l/120),n||i||(i=r),void 0!==n&&(e.deltaX=n),void 0!==i&&(e.deltaY=i),void 0!==r&&(e.delta=r)}},{reg:/^mouse|contextmenu|click|mspointer|(^DOMMouseScroll$)/i,props:["buttons","clientX","clientY","button","offsetX","relatedTarget","which","fromElement","toElement","offsetY","pageX","pageY","screenX","screenY"],fix:function(e,t){var n=void 0,i=void 0,o=void 0,a=e.target,s=t.button;return a&&r(e.pageX)&&!r(t.clientX)&&(n=a.ownerDocument||document,i=n.documentElement,o=n.body,e.pageX=t.clientX+(i&&i.scrollLeft||o&&o.scrollLeft||0)-(i&&i.clientLeft||o&&o.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||o&&o.scrollTop||0)-(i&&i.clientTop||o&&o.clientTop||0)),e.which||void 0===s||(1&s?e.which=1:2&s?e.which=3:4&s?e.which=2:e.which=0),!e.relatedTarget&&e.fromElement&&(e.relatedTarget=e.fromElement===a?e.toElement:e.fromElement),e}}],y=u["default"].prototype;(0,d["default"])(s.prototype,y,{constructor:s,preventDefault:function(){var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=p,y.preventDefault.call(this)},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=f,y.stopPropagation.call(this)}}),t["default"]=s,e.exports=t["default"]},function(e,t){"use strict";function n(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return 1===t.length?i.apply(void 0,t):r.apply(void 0,t)}function i(e){var t=void 0;return"undefined"!=typeof Reflect&&"function"==typeof Reflect.ownKeys?t=Reflect.ownKeys(e.prototype):(t=Object.getOwnPropertyNames(e.prototype),"function"==typeof Object.getOwnPropertySymbols&&(t=t.concat(Object.getOwnPropertySymbols(e.prototype)))),t.forEach(function(t){if("constructor"!==t){var n=Object.getOwnPropertyDescriptor(e.prototype,t);"function"==typeof n.value&&Object.defineProperty(e.prototype,t,r(e,t,n))}}),e}function r(e,t,n){var i=n.value;if("function"!=typeof i)throw new Error("@autobind decorator can only be applied to methods not: "+typeof i);var r=!1;return{configurable:!0,get:function(){if(r||this===e.prototype||this.hasOwnProperty(t))return i;var n=i.bind(this);return r=!0,Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),r=!1,n}}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-(\w)/g,function(e,t){return t.toUpperCase()})}var r=n(120);r.keys().forEach(function(e){var n=r(e);n&&n["default"]&&(n=n["default"]);var o=e.match(/^\.\/([^_][\w-]+)\/index\.web\.tsx?$/);o&&o[1]&&(t[i(o[1])]=n)}),"undefined"!=typeof console&&console.warn&&console.warn("you are using prebuild antd-mobile,\nplease use https://github.com/ant-design/babel-plugin-import to reduce app bundle size.")},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(2),o=i(r),a=n(4),s=i(a),l=n(3),u=i(l),c=n(1),d=i(c),f=n(352),p=i(f),h=function(e){function t(){return(0,o["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){return d["default"].createElement(p["default"],this.props)},t}(d["default"].Component);t["default"]=h,h.Panel=f.Panel,h.defaultProps={prefixCls:"am-accordion"},e.exports=t["default"]},[451,280],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(14),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(10),v=i(y),g=n(15),b=i(g),M=n(31),T=i(M),x=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e=(0,b["default"])(this.props,["children","className","prefixCls","onClick","touchFeedback","activeStyle"]),t=(0,s["default"])(e,2),n=t[0],i=n.children,r=n.className,a=n.prefixCls,l=n.onClick,u=n.touchFeedback,c=n.activeStyle,d=t[1],f=(0,v["default"])({},this.props.style);return u&&(f=(0,v["default"])(f,c)),m["default"].createElement("div",(0,o["default"])({},d,{style:f,className:u?r+" "+a+"-active":""+r,onClick:l}),i)},t}(m["default"].Component);t["default"]=(0,T["default"])(x), e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}function o(e,t,n){function i(){if(M){d["default"].unmountComponentAtNode(M),M.parentNode.removeChild(M),M=null;var e=S.indexOf(i);e!==-1&&S.splice(e,1)}}function r(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=n(e,t);r&&r.then?r.then(function(){i()}):i()}var o,a=(0,b["default"])({},{prefixCls:"am-action-sheet",cancelButtonText:"\u53d6\u6d88"},t),l=a.prefixCls,c=a.className,f=a.transitionName,h=a.maskTransitionName,y=a.maskClosable,g=void 0===y||y,M=document.createElement("div");document.body.appendChild(M),S.push(i);var x=a.title,N=a.message,E=a.options,P=a.destructiveButtonIndex,D=a.cancelButtonIndex,I=a.cancelButtonText,L=[x?u["default"].createElement("h3",{key:"0",className:l+"-title"},x):null,N?u["default"].createElement("div",{key:"1",className:l+"-message"},N):null],j=null,k="normal";!function(){switch(e){case _:k="normal",j=u["default"].createElement("div",(0,T["default"])(a),L,u["default"].createElement("div",{className:l+"-button-list"},E.map(function(e,t){var n,i=(n={},(0,s["default"])(n,l+"-button-list-item",!0),(0,s["default"])(n,l+"-destructive-button",P===t),(0,s["default"])(n,l+"-cancel-button",D===t),n),o={key:t,prefixCls:l+"-button-list-item",className:(0,m["default"])(i),onClick:function(){return r(t)}},a=u["default"].createElement(C["default"],o,e);return D!==t&&P!==t||(a=u["default"].createElement(C["default"],o,e,D===t?u["default"].createElement("span",{className:l+"-cancel-button-mask"}):null)),a})));break;case w:k="share";var t=E.length&&Array.isArray(E[0])||!1,n=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return u["default"].createElement("div",{className:l+"-share-list-item",key:t,onClick:function(){return r(t,n)}},u["default"].createElement("div",{className:l+"-share-list-item-icon"},e.iconName?u["default"].createElement(v["default"],{type:e.iconName}):e.icon),u["default"].createElement("div",{className:l+"-share-list-item-title"},e.title))};j=u["default"].createElement("div",(0,T["default"])(a),L,u["default"].createElement("div",{className:l+"-share"},t?E.map(function(e,t){return u["default"].createElement("div",{key:t,className:l+"-share-list"},e.map(function(e,i){return n(e,i,t)}))}):u["default"].createElement("div",{className:l+"-share-list"},E.map(function(e,t){return n(e,t)})),u["default"].createElement(C["default"],{prefixCls:l+"-share-cancel-button",className:l+"-share-cancel-button",onClick:function(){return r(-1)}},I)))}}();var O=(0,m["default"])((o={},(0,s["default"])(o,c,!!c),(0,s["default"])(o,l+"-"+k,!0),o));return d["default"].render(u["default"].createElement(p["default"],{visible:!0,title:"",footer:"",prefixCls:l,className:O,transitionName:f||"am-slide-up",maskTransitionName:h||"am-fade",onClose:i,maskClosable:g,wrapProps:a.wrapProps||{}},j),M),{close:i}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),s=i(a),l=n(1),u=i(l),c=n(9),d=i(c),f=n(46),p=i(f),h=n(5),m=i(h),y=n(13),v=i(y),g=n(10),b=i(g),M=n(25),T=i(M),x=n(128),C=i(x),_="NORMAL",w="SHARE",S=[];t["default"]={showActionSheetWithOptions:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:r;o(_,e,t)},showShareActionSheetWithOptions:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:r;o(w,e,t)},close:function(){S.forEach(function(e){return e()})}},e.exports=t["default"]},[452,281],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t,n=this.props,i=n.prefixCls,r=n.className,a=n.animating,s=n.toast,l=n.size,u=n.color,c=n.text,d=(0,m["default"])((e={},(0,o["default"])(e,""+i,!0),(0,o["default"])(e,i+"-lg","large"===l),(0,o["default"])(e,i+"-sm","small"===l),(0,o["default"])(e,r,!!r),(0,o["default"])(e,i+"-toast",!!s),e)),f=(0,m["default"])((t={},(0,o["default"])(t,i+"-spinner",!0),(0,o["default"])(t,i+"-spinner-lg",!!s||"large"===l),(0,o["default"])(t,i+"-spinner-white",!!s||"white"===u),t));return a?s?p["default"].createElement("div",{className:d},p["default"].createElement("div",{className:i+"-content"},p["default"].createElement("span",{className:f}),c&&p["default"].createElement("span",{className:i+"-toast"},c))):p["default"].createElement("div",{className:d},p["default"].createElement("span",{className:f}),c&&p["default"].createElement("span",{className:i+"-tip"},c)):null},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-activity-indicator",animating:!0,size:"small",color:"gray",panelColor:"rgba(34,34,34,0.6)",toast:!1},e.exports=t["default"]},[451,282],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.children,r=t.className,a=(0,m["default"])((e={},(0,o["default"])(e,n+"-body",!0),(0,o["default"])(e,r,r),e));return p["default"].createElement("div",{className:a},i)},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-card"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.content,r=t.className,a=t.extra,s=(0,m["default"])((e={},(0,o["default"])(e,n+"-footer",!0),(0,o["default"])(e,r,r),e));return p["default"].createElement("div",{className:s},p["default"].createElement("div",{className:n+"-footer-content"},i),a?p["default"].createElement("div",{className:n+"-footer-extra"},a):null)},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-card"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.className,r=t.title,a=t.thumb,s=t.thumbStyle,l=t.extra,u=(0,m["default"])((e={},(0,o["default"])(e,n+"-header",!0),(0,o["default"])(e,i,i),e));return p["default"].createElement("div",{className:u},p["default"].createElement("div",{className:n+"-header-content"},a?p["default"].createElement("img",{style:s,src:a}):null,r),l?p["default"].createElement("div",{className:n+"-header-extra"},l):null)},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-card",thumbStyle:{}},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=n(135),v=i(y),g=n(133),b=i(g),M=n(134),T=i(M),x=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.full,r=t.children,a=t.className,s=(0,m["default"])((e={},(0,o["default"])(e,n,!0),(0,o["default"])(e,n+"-full",i),(0,o["default"])(e,a,a),e));return p["default"].createElement("div",{className:s},r)},t}(p["default"].Component);t["default"]=x,x.defaultProps={prefixCls:"am-card",full:!1},x.Header=v["default"],x.Body=b["default"],x.Footer=T["default"],e.exports=t["default"]},[451,285],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(6),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(5),v=i(y),g=n(49),b=i(g),M=n(25),T=i(M),x=n(38),C=i(x),_=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.style,r=t.className,a=t.name,l=t.children,u=(0,v["default"])((e={},(0,s["default"])(e,n+"-agree",!0),(0,s["default"])(e,r,r),e)),c=(0,C["default"])(this.props,["style","className"]);return m["default"].createElement("div",(0,o["default"])({},(0,T["default"])(this.props),{className:u,style:i}),m["default"].createElement("label",{className:n+"-agree-label",htmlFor:a},m["default"].createElement(b["default"],c),l))},t}(m["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-checkbox"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(7),a=i(o),s=n(6),l=i(s),u=n(2),c=i(u),d=n(4),f=i(d),p=n(3),h=i(p),m=n(1),y=i(m),v=n(5),g=i(v),b=n(26),M=i(b),T=n(49),x=i(T),C=n(38),_=i(C),w=M["default"].Item,S=function(e){function t(){return(0,c["default"])(this,t),(0,f["default"])(this,e.apply(this,arguments))}return(0,h["default"])(t,e),t.prototype.render=function(){var e,t=this,n=this.props,i=n.prefixCls,o=n.listPrefixCls,s=n.className,u=n.children,c=n.disabled,d=n.checkboxProps,f=void 0===d?{}:d,p=(0,g["default"])((e={},(0,l["default"])(e,i+"-item",!0),(0,l["default"])(e,i+"-item-disabled",c===!0),(0,l["default"])(e,s,s),e)),h=(0,_["default"])(this.props,["listPrefixCls","disabled","checkboxProps"]);c?delete h.onClick:h.onClick=h.onClick||r;var m={};return["name","defaultChecked","checked","onChange","disabled"].forEach(function(e){e in t.props&&(m[e]=t.props[e])}),y["default"].createElement(w,(0,a["default"])({},h,{prefixCls:o,className:p,thumb:y["default"].createElement(x["default"],(0,a["default"])({},f,m))}),u)},t}(y["default"].Component);t["default"]=S,S.defaultProps={prefixCls:"am-checkbox",listPrefixCls:"am-list"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(49),o=i(r),a=n(139),s=i(a),l=n(138),u=i(l);o["default"].CheckboxItem=s["default"],o["default"].AgreeItem=u["default"],t["default"]=o["default"],e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){return(0,T["default"])({prefixCls:"am-picker",pickerPrefixCls:"am-picker-col",popupPrefixCls:"am-picker-popup"},(0,b.getProps)())}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(7),a=i(o),s=n(2),l=i(s),u=n(4),c=i(u),d=n(3),f=i(d),p=n(1),h=i(p),m=n(415),y=i(m),v=n(413),g=i(v),b=n(144),M=n(10),T=i(M),x=function(e){function t(){return(0,l["default"])(this,t),(0,c["default"])(this,e.apply(this,arguments))}return(0,f["default"])(t,e),t.prototype.render=function(){var e=this.props,t=e.children,n=e.value,i=e.defaultDate,r=e.extra,o=e.okText,s=e.dismissText,l=e.popupPrefixCls,u={extra:n?(0,b.formatFn)(this,n):r},c=h["default"].createElement(g["default"],{locale:e.locale,minDate:e.minDate,maxDate:e.maxDate,mode:e.mode,pickerPrefixCls:e.pickerPrefixCls,prefixCls:e.prefixCls,defaultDate:n||i});return h["default"].createElement(y["default"],(0,a["default"])({datePicker:c,WrapComponent:"div",transitionName:"am-slide-up",maskTransitionName:"am-fade"},e,{prefixCls:l,date:n||i,dismissText:h["default"].createElement("span",{className:l+"-header-cancel-button"},s),okText:h["default"].createElement("span",{className:l+"-header-ok-button"},o)}),h["default"].cloneElement(t,t.type&&"ListItem"===t.type.myName?u:{}))},t}(h["default"].Component);t["default"]=x,x.defaultProps=r(),e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(417);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return i(r)["default"]}}),e.exports=t["default"]},function(e,t,n){"use strict";n(83)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=void 0;return t="time"===e?"HH:mm":"datetime"===e?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"}function o(e,t){var n=e.props.format,i="undefined"==typeof n?"undefined":(0,l["default"])(n);return"string"===i?t.format(i):"function"===i?n(t):t.format(r(e.props.mode))}function a(){return{mode:"datetime",locale:c["default"],extra:"\u8bf7\u9009\u62e9",defaultDate:(0,f["default"])(),onChange:function(){},okText:"\u786e\u5b9a",dismissText:"\u53d6\u6d88",title:""}}Object.defineProperty(t,"__esModule",{value:!0});var s=n(34),l=i(s);t.formatFn=o,t.getProps=a;var u=n(142),c=i(u),d=n(106),f=i(d)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(14),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(360),v=i(y),g=n(15),b=i(g),M=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e=(0,b["default"])(this.props,["prefixCls","children"]),t=(0,s["default"])(e,2),n=t[0],i=n.prefixCls,r=n.children,a=t[1];return m["default"].createElement(v["default"],(0,o["default"])({prefixCls:i},a),r)},t}(m["default"].Component);t["default"]=M,M.defaultProps={prefixCls:"am-drawer",enableDragHandle:!1},e.exports=t["default"]},[451,288],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.direction,i=t.wrap,r=t.justify,a=t.align,s=t.alignContent,l=t.className,u=t.children,c=t.prefixCls,d=t.style,f=t.onClick,h=(0,m["default"])((e={},(0,o["default"])(e,c,!0),(0,o["default"])(e,c+"-dir-row","row"===n),(0,o["default"])(e,c+"-dir-row-reverse","row-reverse"===n),(0,o["default"])(e,c+"-dir-column","column"===n),(0,o["default"])(e,c+"-dir-column-reverse","column-reverse"===n),(0,o["default"])(e,c+"-nowrap","nowrap"===i),(0,o["default"])(e,c+"-wrap","wrap"===i),(0,o["default"])(e,c+"-wrap-reverse","wrap-reverse"===i),(0,o["default"])(e,c+"-justify-start","start"===r),(0,o["default"])(e,c+"-justify-end","end"===r),(0,o["default"])(e,c+"-justify-center","center"===r),(0,o["default"])(e,c+"-justify-between","between"===r),(0,o["default"])(e,c+"-justify-around","around"===r),(0,o["default"])(e,c+"-align-top","top"===a||"start"===a),(0,o["default"])(e,c+"-align-middle","middle"===a||"center"===a),(0,o["default"])(e,c+"-align-bottom","bottom"===a||"end"===a),(0,o["default"])(e,c+"-align-baseline","baseline"===a),(0,o["default"])(e,c+"-align-stretch","stretch"===a),(0,o["default"])(e,c+"-align-content-start","start"===s),(0,o["default"])(e,c+"-align-content-end","end"===s),(0,o["default"])(e,c+"-align-content-center","center"===s),(0,o["default"])(e,c+"-align-content-between","between"===s),(0,o["default"])(e,c+"-align-content-around","around"===s),(0,o["default"])(e,c+"-align-content-stretch","stretch"===s),(0,o["default"])(e,l,l),e));return p["default"].createElement("div",{className:h,style:d,onClick:f},u)},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-flexbox",align:"center",onClick:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.children,i=t.className,r=t.prefixCls,a=t.style,s=t.onClick,l=(0,m["default"])((e={},(0,o["default"])(e,r+"-item",!0),(0,o["default"])(e,i,i),e));return p["default"].createElement("div",{className:l,style:a,onClick:s},n)},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-flexbox"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=n(32),v=i(y),g=n(77),b=i(g),M=function(e){function t(){(0,s["default"])(this,t);var n=(0,u["default"])(this,e.apply(this,arguments));return n.clientWidth=document.documentElement.clientWidth,n}return(0,d["default"])(t,e),t.prototype.render=function(){for(var e,t=this,n=this.props,i=n.prefixCls,r=n.className,a=n.data,s=n.hasLine,l=n.columnNum,u=n.isCarousel,c=n.carouselMaxRow,d=n.onClick,f=void 0===d?function(){}:d,h=a&&a.length||0,y=Math.ceil(h/l),g=this.props.renderItem||function(e){return p["default"].createElement("div",{className:i+"-item-contain column-num-"+l,style:{height:t.clientWidth/l+"px"}},p["default"].createElement("img",{className:i+"-icon",src:e.icon}),p["default"].createElement("div",{className:i+"-text"},e.text))},M=[],T=0;T<y;T++){for(var x=[],C=function(e){var t=T*l+e;t<h?!function(){var e=a&&a[t];x.push(p["default"].createElement(v["default"].Item,{key:"griditem-"+t,className:i+"-item",onClick:function(){return f(e,t)}},g(e,t)))}():x.push(p["default"].createElement(v["default"].Item,{key:"griditem-"+t}))},_=0;_<l;_++)C(_);M.push(p["default"].createElement(v["default"],{justify:"center",align:"stretch",key:"gridline-"+T},x))}var w=Math.ceil(y/c),S=[];if(u&&w>1)for(var N=0;N<w;N++){for(var E=[],P=0;P<c;P++){var D=N*c+P;D<y?E.push(M[D]):E.push(p["default"].createElement("div",{key:"gridline-"+D}))}S.push(p["default"].createElement("div",{key:"pageitem-"+N,className:i+"-carousel-page"},E))}return p["default"].createElement("div",{className:(0,m["default"])((e={},(0,o["default"])(e,i,!0),(0,o["default"])(e,i+"-line",s),(0,o["default"])(e,r,r),e))},u&&w>1?p["default"].createElement(b["default"],null,S):M)},t}(p["default"].Component);t["default"]=M,M.defaultProps={data:[],hasLine:!0,isCarousel:!1,columnNum:4,carouselMaxRow:2,prefixCls:"am-grid"},e.exports=t["default"]},function(e,t,n){"use strict";n(8),n(33),n(78),n(290)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),a=i(o),s=n(2),l=i(s),u=n(4),c=i(u),d=n(3),f=i(d),p=n(1),h=i(p),m=n(5),y=i(m),v=n(88),g=i(v),b=n(32),M=i(b),T=n(85),x=i(T),C=function(e){function t(){(0,l["default"])(this,t);var n=(0,c["default"])(this,e.apply(this,arguments));return n.getOrientation=function(e,t){if(/iphone|ipad/i.test(navigator.userAgent)){var n=new FileReader;n.onload=function(e){var n=new DataView(e.target.result);if(65496!==n.getUint16(0,!1))return t(-2);for(var i=n.byteLength,r=2;r<i;){var o=n.getUint16(r,!1);if(r+=2,65505===o){var a=n.getUint32(r+=2,!1);if(1165519206!==a)return t(-1);var s=18761===n.getUint16(r+=6,!1);r+=n.getUint32(r+4,s);var l=n.getUint16(r,s);r+=2;for(var u=0;u<l;u++)if(274===n.getUint16(r+12*u,s))return t(n.getUint16(r+12*u+8,s))}else{if(65280!==(65280&o))break;r+=n.getUint16(r,!1)}}return t(-1)},n.readAsArrayBuffer(e.slice(0,65536))}else t("-1")},n.removeImage=function(e){var t=[],i=n.props.files,r=void 0===i?[]:i;r.forEach(function(n,i){e!==i&&t.push(n)}),n.props.onChange&&n.props.onChange(t,"remove",e)},n.addImage=function(e){var t=n.props.files,i=void 0===t?[]:t,r=i.concat(e);n.props.onChange&&n.props.onChange(r,"add")},n.onImageClick=function(e){n.props.onImageClick&&n.props.onImageClick(e,n.props.files)},n.onFileChange=function(){var e=n.refs.fileSelectorInput;e.files&&e.files.length&&!function(){var t=e.files[0],i=new FileReader;i.onload=function(i){var r=i.target.result;if(!r)return void x["default"].fail("\u56fe\u7247\u83b7\u53d6\u5931\u8d25");var o=1;n.getOrientation(t,function(i){i>0&&(o=i),n.addImage({url:r,orientation:o,file:t}),e.value=""})},i.readAsDataURL(t)}()},n}return(0,f["default"])(t,e),t.prototype.render=function(){var e,t=this,n=this.props,i=n.prefixCls,r=n.style,o=n.className,s=n.files,l=void 0===s?[]:s,u=n.selectable,c=n.onAddImageClick,d=window.devicePixelRatio||1,f=[],p=(document.documentElement.clientWidth-18*d-6*d*3)/4,m=(0,y["default"])((e={},(0,a["default"])(e,""+i,!0),(0,a["default"])(e,o,o),e)),v={width:p+"px",height:p+"px"};return l.forEach(function(e,n){f.push(h["default"].createElement("div",{key:n,className:i+"-item",style:v},h["default"].createElement("div",{className:i+"-item-remove",onClick:function(){t.removeImage(n)}}),h["default"].createElement("div",{className:i+"-item-content",onClick:function(){t.onImageClick(n)},style:{backgroundImage:"url("+e.url+")"}})))}),h["default"].createElement("div",{className:m,style:r},h["default"].createElement("div",{className:i+"-list"},h["default"].createElement(g["default"],{size:"md"},h["default"].createElement(M["default"],{wrap:"wrap"},f,u&&h["default"].createElement("div",{className:i+"-item "+i+"-upload-btn",style:v,onClick:function(){c&&c()}},c?null:h["default"].createElement("input",{style:v,ref:"fileSelectorInput",type:"file",accept:"image/jpg,image/jpeg,image/png,image/gif",onChange:function(){t.onFileChange()}}))))))},t}(h["default"].Component);t["default"]=C,C.defaultProps={prefixCls:"am-image-picker",files:[],onChange:r,onImageClick:r,selectable:!0},e.exports=t["default"]},function(e,t,n){"use strict";n(8),n(89),n(33),n(86),n(292)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}function o(e){return"undefined"==typeof e||null===e?"":e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),s=i(a),l=n(6),u=i(l),c=n(2),d=i(c),f=n(4),p=i(f),h=n(3),m=i(h),y=n(1),v=i(y),g=n(5),b=i(g),M=n(38),T=i(M),x=function(e){function t(n){(0,d["default"])(this,t);var i=(0,p["default"])(this,e.call(this,n));return i.onInputChange=function(e){var t=e.target.value,n=i.props,r=n.onChange,o=n.type;switch(o){case"text":break;case"bankCard":t=t.replace(/\D/g,""),t=t.replace(/\D/g,"").replace(/(....)(?=.)/g,"$1 ");break;case"phone":t=t.replace(/\D/g,"").substring(0,11);var a=t.length;a>3&&a<8?t=t.substr(0,3)+" "+t.substr(3):a>=8&&(t=t.substr(0,3)+" "+t.substr(3,4)+" "+t.substr(7));break;case"number":t=t.replace(/\D/g,"");break;case"password":}r&&r(t)},i.onInputBlur=function(e){i.debounceTimeout=setTimeout(function(){i.setState({focus:!1})},300);var t=e.target.value;i.props.onBlur&&i.props.onBlur(t)},i.onInputFocus=function(e){i.setState({focus:!0});var t=e.target.value;i.props.onFocus&&i.props.onFocus(t)},i.onExtraClick=function(e){i.props.onExtraClick&&i.props.onExtraClick(e)},i.onErrorClick=function(e){i.props.onErrorClick&&i.props.onErrorClick(e)},i.clearInput=function(){"password"!==i.props.type&&i.props.updatePlaceholder&&i.setState({placeholder:i.props.value}),i.props.onChange&&i.props.onChange("")},i.state={focus:!1,placeholder:i.props.placeholder},i}return(0,m["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"placeholder"in e&&this.state.placeholder!==e.placeholder&&this.setState({placeholder:e.placeholder})},t.prototype.componentWillUnmount=function(){this.debounceTimeout&&clearTimeout(this.debounceTimeout)},t.prototype.render=function(){var e,t,n=this.props,i=n.prefixCls,r=n.prefixListCls,a=n.type,l=n.value,c=n.defaultValue,d=n.name,f=n.editable,p=n.disabled,h=n.style,m=n.clear,y=n.children,g=n.error,M=n.className,x=n.extra,C=n.labelNumber,_=n.maxLength,w=(0,T["default"])(this.props,["prefixCls","prefixListCls","editable","style","clear","children","error","className","extra","labelNumber","onExtraClick","onErrorClick","updatePlaceholder"]),S=this.state,N=S.focus,E=S.placeholder,P=(0,b["default"])((e={},(0,u["default"])(e,r+"-item",!0),(0,u["default"])(e,i+"-item",!0),(0,u["default"])(e,i+"-disabled",p),(0,u["default"])(e,i+"-error",g),(0,u["default"])(e,i+"-focus",N),(0,u["default"])(e,M,M),e)),D=(0,b["default"])((t={},(0,u["default"])(t,i+"-label",!0),(0,u["default"])(t,i+"-label-2",2===C),(0,u["default"])(t,i+"-label-3",3===C),(0,u["default"])(t,i+"-label-4",4===C),(0,u["default"])(t,i+"-label-5",5===C),(0,u["default"])(t,i+"-label-6",6===C),(0,u["default"])(t,i+"-label-7",7===C),t)),I="text";"bankCard"===a||"phone"===a?I="tel":"password"===a&&(I="password");var L=void 0;L="value"in this.props?{value:o(l)}:{defaultValue:c};var j=void 0;return"number"===a&&(j={pattern:"[0-9]*"}),v["default"].createElement("div",{className:P,style:h},y?v["default"].createElement("div",{className:D},y):null,v["default"].createElement("div",{className:i+"-control"},v["default"].createElement("input",(0,s["default"])({ref:"input"},j,w,L,{type:I,maxLength:_,name:d,placeholder:E,onChange:this.onInputChange,onBlur:this.onInputBlur,onFocus:this.onInputFocus,readOnly:!f,disabled:p}))),m&&f&&!p&&l&&l.length>0?v["default"].createElement("div",{className:i+"-clear",onClick:this.clearInput}):null,g?v["default"].createElement("div",{className:i+"-error-extra",onClick:this.onErrorClick}):null,""!==x?v["default"].createElement("div",{className:i+"-extra",onClick:this.onExtraClick},x):null)},t}(v["default"].Component);x.defaultProps={prefixCls:"am-input",prefixListCls:"am-list",type:"text",editable:!0,disabled:!1,placeholder:"",clear:!1,onChange:r,onBlur:r,onFocus:r,extra:"",onExtraClick:r,error:!1,onErrorClick:r,labelNumber:4,updatePlaceholder:!1},t["default"]=x,e.exports=t["default"]},[453,293],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(72),m=i(h),y=n(80),v=i(y),g=m["default"].IndexedList,b=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e=(0,v["default"])(this.props,!0),t=e.restProps,n=e.extraProps;return p["default"].createElement(g,(0,o["default"])({ref:"indexedList",sectionHeaderClassName:"am-indexed-list-section-header am-list-body",sectionBodyClassName:"am-indexed-list-section-body am-list-body"},t,n),this.props.children)},t}(p["default"].Component);t["default"]=b,b.defaultProps={prefixCls:"am-indexed-list",listPrefixCls:"am-list",listViewPrefixCls:"am-list-view"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(72),m=i(h),y=n(80),v=i(y),g=n(155),b=i(g),M=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e=(0,v["default"])(this.props,!1),t=e.restProps,n=e.extraProps,i=this.props,r=i.useZscroller,a=i.refreshControl;return a&&(r=!0),p["default"].createElement(m["default"],(0,o["default"])({ref:"listview"},t,n,{useZscroller:r}))},t}(p["default"].Component);t["default"]=M,M.defaultProps={prefixCls:"am-list-view",listPrefixCls:"am-list"},M.DataSource=m["default"].DataSource,M.IndexedList=b["default"],e.exports=t["default"]},[453,294],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=t.Brief=void 0;var r=n(7),o=i(r),a=n(6),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(5),v=i(y),g=n(25),b=i(g),M=t.Brief=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){return m["default"].createElement("div",{className:"am-list-brief",style:this.props.style},this.props.children)},t}(m["default"].Component),T=function(e){function t(n){(0,u["default"])(this,t);var i=(0,d["default"])(this,e.call(this,n));return i.onClick=function(e){i.props.onClick&&i.props.onClick(e)},i.onTouchStart=function(){i.props.onClick&&i.setState({hover:!0})},i.onTouchEnd=function(){i.props.onClick&&i.setState({hover:!1})},i.state={hover:!1},i}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t,n,i=this.props,r=i.prefixCls,a=i.thumb,l=i.arrow,u=i.error,c=i.children,d=i.extra,f=i.className,p=i.align,h=i.multipleLine,y=i.wrap,g=i.style,M=this.state.hover,T=void 0,x=void 0,C=(0,v["default"])((e={},(0,s["default"])(e,r+"-item",!0),(0,s["default"])(e,r+"-item-error",u),(0,s["default"])(e,r+"-item-top","top"===p),(0,s["default"])(e,r+"-item-middle","middle"===p),(0,s["default"])(e,r+"-item-bottom","bottom"===p),(0,s["default"])(e,r+"-item-hover",M),(0,s["default"])(e,f,f),e)),_=(0,v["default"])((t={},(0,s["default"])(t,r+"-line",!0),(0,s["default"])(t,r+"-line-multiple",h),(0,s["default"])(t,r+"-line-wrap",y),t)),w=(0,v["default"])((n={},(0,s["default"])(n,r+"-arrow",!0),(0,s["default"])(n,r+"-arrow-horizontal","horizontal"===l),(0,s["default"])(n,r+"-arrow-vertical","down"===l||"up"===l),(0,s["default"])(n,r+"-arrow-vertical-up","up"===l),n));return a&&(T="string"==typeof a?m["default"].createElement("div",{className:r+"-thumb"},m["default"].createElement("img",{src:a})):m["default"].createElement("div",{className:r+"-thumb"},a)),x=""!==l?m["default"].createElement("div",{className:w}):null,m["default"].createElement("div",(0,o["default"])({},(0,b["default"])(this.props),{className:C,onClick:this.onClick,onTouchStart:this.onTouchStart,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchEnd,style:g}),T,m["default"].createElement("div",{className:_},""!==c?m["default"].createElement("div",{className:r+"-content"},c):null,""!==d?m["default"].createElement("div",{className:r+"-extra"},d):null,x))},t}(m["default"].Component);t["default"]=T,T.Brief=M,T.defaultProps={prefixCls:"am-list",thumb:"",arrow:"",children:"",extra:"",error:!1,multipleLine:!1,align:"middle",wrap:!1},T.myName="ListItem"},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=n(26),v=i(y),g=n(51),b=i(g),M=function(e){function t(n){(0,s["default"])(this,t);var i=(0,u["default"])(this,e.call(this,n));return i.onClick=function(e){i.setState({value:[e]}),i.props.onChange&&i.props.onChange(e)},i.state={value:i.props.value,data:i.props.data},i}return(0,d["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"data"in e&&this.setState({data:e.data})},t.prototype.render=function(){var e,t=this,n=this.state,i=n.value,r=void 0===i?[]:i,a=n.data,s=void 0===a?[]:a,l=this.props,u=l.className,c=l.prefixCls,d=l.radioPrefixCls,f=(0,m["default"])((e={},(0,o["default"])(e,""+c,!0),(0,o["default"])(e,u,u),e)),h=[];return s.forEach(function(e,n){var i,a=(0,m["default"])((i={},(0,o["default"])(i,d+"-item",!0),(0,o["default"])(i,c+"-item-selected",r.length>0&&r[0].value===e.value),(0,o["default"])(i,c+"-item-disabled",e.disabled),i));h.push(p["default"].createElement(v["default"].Item,{className:a,key:n,extra:p["default"].createElement(b["default"],{ checked:r.length>0&&r[0].value===e.value,disabled:e.disabled,onChange:t.onClick.bind(t,e)})},e.label))}),p["default"].createElement(v["default"],{style:{paddingTop:0},className:f},h)},t}(p["default"].Component);t["default"]=M,M.defaultProps={prefixCls:"am-sub-menu",radioPrefixCls:"am-radio",value:[],data:[],onChange:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=n(10),v=i(y),g=n(159),b=i(g),M=n(26),T=i(M),x=n(32),C=i(x),_=function(e){function t(n){(0,s["default"])(this,t);var i=(0,u["default"])(this,e.call(this,n));i.onClickListItem=function(e){e.isLeaf===!0&&i.setState({firstValue:e.value,SubMenuData:[]},function(){i.props.onChange&&i.props.onChange([e.value])}),i.setState({firstValue:e.value,SubMenuData:e.children||[]})},i.onClickSubMenuItem=function(e){var t=i.props,n=t.level,r=t.onChange;setTimeout(function(){r&&r(2===n?[i.state.firstValue,e.value]:[e.value])},300)};var r=n.data,o=n.value,a=n.level;if(2!==a)return i.state={SubMenuData:r},(0,u["default"])(i);if(o.length>0){var l=r.filter(function(e){return e.value===(o.length>0&&o[0]||null)})[0].children||[];return i.state={SubMenuData:l,firstValue:o[0]||""},(0,u["default"])(i)}var c=r[0].children||[];return r[0].isLeaf?i.state={SubMenuData:[],firstValue:""}:i.state={SubMenuData:c,firstValue:r[0].value},i}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this,n=this.props,i=n.className,r=n.data,a=void 0===r?[]:r,s=n.prefixCls,l=n.value,u=void 0===l?[]:l,c=n.level,d=n.style,f=this.props.height;f||(f=document.documentElement.clientHeight/2);var h={height:Math.round(f)+"px",overflowY:"scroll"},y=this.state,g=y.SubMenuData,M=y.firstValue,x=(0,m["default"])((e={},(0,o["default"])(e,s,!0),(0,o["default"])(e,i,!!i),e)),_=a.map(function(e,n){return p["default"].createElement(T["default"].Item,{className:e.value===M?s+"-selected":"",onClick:t.onClickListItem.bind(t,e),key:"listitem-1-"+n},e.label)});return p["default"].createElement("div",{className:x,style:(0,v["default"])({},d,h)},p["default"].createElement(C["default"],{align:"top"},2===c?p["default"].createElement(C["default"].Item,{style:h},p["default"].createElement(T["default"],null,_)):null,p["default"].createElement(C["default"].Item,{style:h},p["default"].createElement(b["default"],{value:g.filter(function(e){return e.value===(u.length&&u[u.length-1])}),data:g,onChange:this.onClickSubMenuItem}))))},t}(p["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-menu",value:[],data:[],level:2,onChange:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";n(8),n(79),n(33),n(20),n(84),n(296)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(6),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(5),v=i(y),g=n(10),b=i(g),M=n(31),T=i(M),x=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.button,i=t.prefixCls,r=t.touchFeedback,a=(0,b["default"])({},this.props);["button","prefixCls","touchFeedback","activeStyle"].forEach(function(e){a.hasOwnProperty(e)&&delete a[e]});var l=(0,v["default"])((e={},(0,s["default"])(e,i+"-button",!0),(0,s["default"])(e,i+"-button-active",r),e)),u={};if(n.style&&(u=n.style,"string"==typeof u)){var c={cancel:{fontWeight:"bold"},"default":{},destructive:{color:"red"}};u=c[u]||{}}return m["default"].createElement("a",(0,o["default"])({className:l,style:u,href:"#",onClick:function(e){e.preventDefault(),n.onPress&&n.onPress()}},a),n.text||"Button")},t}(m["default"].Component);t["default"]=(0,T["default"])(x),e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(){function e(){s["default"].unmountComponentAtNode(a),a.parentNode.removeChild(a)}var t=arguments.length<=0?void 0:arguments[0],n=arguments.length<=1?void 0:arguments[1],i=(arguments.length<=2?void 0:arguments[2])||[{text:"\u786e\u5b9a"}];if(t||n){var r="am-modal",a=document.createElement("div");document.body.appendChild(a);var l=i.map(function(t){var n=t.onPress||function(){};return t.onPress=function(){n(),e()},t});s["default"].render(o["default"].createElement(u["default"],{visible:!0,transparent:!0,prefixCls:r,title:t,transitionName:"am-zoom",closable:!1,maskClosable:!1,footer:l,maskTransitionName:"am-fade"},o["default"].createElement("div",{style:{zoom:1,overflow:"hidden"}},n)),a)}};var r=n(1),o=i(r),a=n(9),s=i(a),l=n(50),u=i(l);e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(){function e(e){var t=e.target,n=t.getAttribute("type");p[n]=t.value}function t(){s["default"].unmountComponentAtNode(m),m.parentNode.removeChild(m)}function n(e){var t=p.text||"",n=p.password||"";return"login-password"===f?e(t,n):e("secure-text"===f?n:t)}for(var i=arguments.length,r=Array(i),a=0;a<i;a++)r[a]=arguments[a];if(r&&r[2]){var l="am-modal",c=r[0],d=void 0,f=r[3]||"default",p={};switch(f){case"login-password":d=o["default"].createElement("div",null,o["default"].createElement("div",{className:l+"-input"},o["default"].createElement("input",{type:"text",defaultValue:"",ref:function(e){return setTimeout(function(){e.focus()},500)},onChange:e})),o["default"].createElement("div",{className:l+"-input"},o["default"].createElement("input",{type:"password",defaultValue:"",onChange:e})));break;case"secure-text":d=o["default"].createElement("div",null,o["default"].createElement("div",{className:l+"-input"},o["default"].createElement("input",{type:"password",defaultValue:"",ref:function(e){return setTimeout(function(){e.focus()},500)},onChange:e})));break;case"plain-text":case"default":default:d=o["default"].createElement("div",null,o["default"].createElement("div",{className:l+"-input"},o["default"].createElement("input",{type:"text",defaultValue:"",ref:function(e){return setTimeout(function(){e.focus()},500)},onChange:e})))}var h=o["default"].createElement("div",null,r[1],d),m=document.createElement("div");document.body.appendChild(m);var y=void 0;y="function"==typeof r[2]?[{text:"\u53d6\u6d88"},{text:"\u786e\u5b9a",onPress:function(){n(r[2])}}]:r[2].map(function(e){return{text:e.text,onPress:function(){e.onPress&&n(e.onPress)}}});var v=y.map(function(e){var n=e.onPress||function(){};return e.onPress=function(){n(),t()},e});s["default"].render(o["default"].createElement(u["default"],{visible:!0,transparent:!0,prefixCls:l,title:c,closable:!1,maskClosable:!1,transitionName:"am-zoom",footer:v,maskTransitionName:"am-fade"},o["default"].createElement("div",{style:{zoom:1,overflow:"hidden"}},h)),m)}};var r=n(1),o=i(r),a=n(9),s=i(a),l=n(50),u=i(l);e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(6),s=i(a),l=n(14),u=i(l),c=n(2),d=i(c),f=n(4),p=i(f),h=n(3),m=i(h),y=n(1),v=i(y),g=n(5),b=i(g),M=n(13),T=i(M),x=n(15),C=i(x),_=function(e){function t(){return(0,d["default"])(this,t),(0,p["default"])(this,e.apply(this,arguments))}return(0,m["default"])(t,e),t.prototype.render=function(){var e,t=(0,C["default"])(this.props,["prefixCls","children","mode","className","iconName","leftContent","rightContent","onLeftClick"]),n=(0,u["default"])(t,2),i=n[0],r=i.prefixCls,a=i.children,l=i.mode,c=i.className,d=i.iconName,f=i.leftContent,p=i.rightContent,h=i.onLeftClick,m=n[1],y=(0,b["default"])((e={},(0,s["default"])(e,c,c),(0,s["default"])(e,r,!0),(0,s["default"])(e,r+"-"+l,!0),e));return v["default"].createElement("div",(0,o["default"])({},m,{className:y}),v["default"].createElement("div",{className:r+"-left",onClick:h},d?v["default"].createElement("span",{className:r+"-left-icon"},v["default"].createElement(T["default"],{type:d})):null,v["default"].createElement("span",{className:r+"-left-content"},f)),v["default"].createElement("div",{className:r+"-title"},a),v["default"].createElement("div",{className:r+"-right"},p))},t}(v["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-navbar",mode:"dark",iconName:"left",onLeftClick:function(){}},e.exports=t["default"]},[452,298],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(6),s=i(a),l=n(14),u=i(l),c=n(2),d=i(c),f=n(4),p=i(f),h=n(3),m=i(h),y=n(1),v=i(y),g=n(5),b=i(g),M=n(25),T=i(M),x=n(15),C=i(x),_=n(13),w=i(_),S=function(e){function t(n){(0,d["default"])(this,t);var i=(0,p["default"])(this,e.call(this,n));return i.onClick=function(){var e=i.props,t=e.mode,n=e.onClick;n&&n(),"closable"===t&&i.setState({show:!1})},i.state={show:!0},i}return(0,m["default"])(t,e),t.prototype.render=function(){var e,t=(0,C["default"])(this.props,["mode","type","onClick","children","className","prefixCls"]),n=(0,u["default"])(t,2),i=n[0],r=i.mode,a=i.type,l=i.onClick,c=i.children,d=i.className,f=i.prefixCls,p=n[1],h={},m=null;"closable"===r?m=v["default"].createElement("div",{className:f+"-operation",onClick:this.onClick},v["default"].createElement(w["default"],{type:"cross",size:"md"})):("link"===r&&(m=v["default"].createElement("div",{className:f+"-operation"},v["default"].createElement(w["default"],{type:"right",size:"md"}))),h.onClick=l);var y={success:"check-circle",error:"cross-circle",warn:"exclamation-circle",question:"question-circle"},g=a?v["default"].createElement("div",{className:f+"-icon"},v["default"].createElement(w["default"],{type:y[a]||"info-circle",size:"xxs"})):null,M=(0,b["default"])((e={},(0,s["default"])(e,f,!0),(0,s["default"])(e,d,!!d),e));return this.state.show?v["default"].createElement("div",(0,o["default"])({},(0,T["default"])(this.props),{className:M},p,h),g,v["default"].createElement("div",{className:f+"-content"},c),m):null},t}(v["default"].Component);t["default"]=S,S.defaultProps={prefixCls:"am-notice-bar",mode:"",onClick:function(){}},e.exports=t["default"]},[452,299],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),a=i(o),s=n(2),l=i(s),u=n(4),c=i(u),d=n(3),f=i(d),p=n(1),h=i(p),m=n(5),y=i(m),v=n(47),g=i(v),b=n(32),M=i(b),T=function(e){function t(n){(0,l["default"])(this,t);var i=(0,c["default"])(this,e.call(this,n));return i.state={current:n.current},i.onPrev=i.onPrev.bind(i),i.onNext=i.onNext.bind(i),i}return(0,f["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){this.setState({current:e.current})},t.prototype._hasPrev=function(){return this.state.current>0},t.prototype._hasNext=function(){return this.state.current<this.props.total},t.prototype._handleChange=function(e){return this.setState({current:e}),this.props.onChange&&this.props.onChange(e),e},t.prototype.onPrev=function(){this._handleChange(this.state.current-1)},t.prototype.onNext=function(){this._handleChange(this.state.current+1)},t.prototype.getIndexes=function(e){for(var t=[],n=0;n<e;n++)t.push(n);return t},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.className,i=e.mode,r=e.total,o=e.simple,s=e.prevText,l=e.nextText,u=this.state.current,c=(0,y["default"])((0,a["default"])({className:n},t+"-wrap",!0)),d=void 0;switch(i){case"button":d=h["default"].createElement(M["default"],null,h["default"].createElement(M["default"].Item,{className:t+"-wrap-btn "+t+"-wrap-btn-prev"},h["default"].createElement(g["default"],{inline:!0,disabled:u<=0,onClick:this.onPrev},s)),this.props.children?h["default"].createElement(M["default"].Item,null,this.props.children):!o&&h["default"].createElement(M["default"].Item,{className:c},h["default"].createElement("span",{className:"active"},u+1),"/",h["default"].createElement("span",null,r)),h["default"].createElement(M["default"].Item,{className:t+"-wrap-btn "+t+"-wrap-btn-next"},h["default"].createElement(g["default"],{disabled:u>=r-1,inline:!0,onClick:this.onNext},l)));break;case"number":d=h["default"].createElement("div",{className:c},h["default"].createElement("span",{className:"active"},u+1),"/",h["default"].createElement("span",null,r));break;case"pointer":var f=this.getIndexes(r);d=h["default"].createElement("div",{className:c},f.map(function(e){var n,i=(0,y["default"])((n={},(0,a["default"])(n,t+"-wrap-dot",!0),(0,a["default"])(n,t+"-wrap-dot-active",e===u),n));return h["default"].createElement("div",{className:i,key:"dot-"+e},h["default"].createElement("span",null))}));break;default:d=!1}return h["default"].createElement("div",{className:t},d)},t}(h["default"].Component);t["default"]=T,T.defaultProps={prefixCls:"am-pagination",mode:"button",current:0,simple:!1,prevText:"Prev",nextText:"Next",onChange:r},e.exports=t["default"]},function(e,t,n){"use strict";n(8),n(48),n(33),n(300)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){var e=function(e){return e.join(",")};return{prefixCls:"am-picker",pickerPrefixCls:"am-picker-col",popupPrefixCls:"am-picker-popup",format:e,style:{left:0,bottom:0},cols:3,value:[],extra:"\u8bf7\u9009\u62e9",okText:"\u786e\u5b9a",dismissText:"\u53d6\u6d88",title:""}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(7),a=i(o),s=n(2),l=i(s),u=n(4),c=i(u),d=n(3),f=i(d),p=n(1),h=i(p),m=n(412),y=i(m),v=n(410),g=i(v),b=n(74),M=i(b),T=function(e){function t(){(0,l["default"])(this,t);var n=(0,c["default"])(this,e.apply(this,arguments));return n.getSel=function(){var e=n.props.value||[],t=(0,M["default"])(n.props.data,function(t,n){return t.value===e[n]});return n.props.format&&n.props.format(t.map(function(e){return e.label}))},n}return(0,f["default"])(t,e),t.prototype.render=function(){var e=this.props,t=e.children,n=e.value,i=e.extra,r=e.okText,o=e.dismissText,s=e.popupPrefixCls,l={extra:this.getSel()||i},u=h["default"].cloneElement(t,t.type&&"ListItem"===t.type.myName?l:{}),c=h["default"].createElement(g["default"],{prefixCls:e.prefixCls,pickerPrefixCls:e.pickerPrefixCls,data:e.data,cols:e.cols,onChange:e.onPickerChange});return h["default"].createElement(y["default"],(0,a["default"])({cascader:c,WrapComponent:"div",transitionName:"am-slide-up",maskTransitionName:"am-fade"},e,{prefixCls:s,value:n,dismissText:h["default"].createElement("span",{className:s+"-header-cancel-button"},o),okText:h["default"].createElement("span",{className:s+"-header-ok-button"},r)}),u)},t}(h["default"].Component);t["default"]=T,T.defaultProps=r(),e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return e};return y["default"].Children.map(e,function(e,n){var i=t(e,n);return i&&i.props&&i.props.children?y["default"].cloneElement(i,{},r(i.props.children,t)):i})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(7),a=i(o),s=n(14),l=i(s),u=n(2),c=i(u),d=n(4),f=i(d),p=n(3),h=i(p),m=n(1),y=i(m),v=n(113),g=i(v),b=n(173),M=i(b),T=n(15),x=i(T),C=function(e){function t(){return(0,c["default"])(this,t),(0,f["default"])(this,e.apply(this,arguments))}return(0,h["default"])(t,e),t.prototype.render=function(){var e=(0,x["default"])(this.props,["children","prefixCls","placement","trigger","overlay","onSelect","popupAlign"]),t=(0,l["default"])(e,2),n=t[0],i=n.children,o=n.prefixCls,s=n.placement,u=n.trigger,c=n.overlay,d=n.onSelect,f=n.popupAlign,p=t[1],h=r(c,function(e,t){var n={firstItem:!1,onClick:function(){}};return e&&e.type&&"PopoverItem"===e.type.myName&&!e.props.disabled?(n.onClick=function(){d(e)},n.firstItem=0===t,y["default"].cloneElement(e,n)):e});return y["default"].createElement(g["default"],(0,a["default"])({prefixCls:o,placement:s,trigger:u,overlay:h,popupAlign:f},p),i)},t}(y["default"].Component);t["default"]=C,C.defaultProps={prefixCls:"am-popover",placement:"bottomRight",popupAlign:{overflow:{adjustY:0,adjustX:0}},trigger:["click"],onSelect:function(){}},C.Item=M["default"],e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(6),s=i(a),l=n(14),u=i(l),c=n(2),d=i(c),f=n(4),p=i(f),h=n(3),m=i(h),y=n(1),v=i(y),g=n(5),b=i(g),M=n(10),T=i(M),x=n(13),C=i(x),_=n(15),w=i(_),S=n(31),N=i(S),E=function(e){function t(){return(0,d["default"])(this,t),(0,p["default"])(this,e.apply(this,arguments))}return(0,m["default"])(t,e),t.prototype.render=function(){var e,t=(0,w["default"])(this.props,["children","className","prefixCls","iconName","disabled","touchFeedback","activeStyle","firstItem"]),n=(0,u["default"])(t,2),i=n[0],r=i.children,a=i.className,l=i.prefixCls,c=i.iconName,d=i.disabled,f=i.touchFeedback,p=i.activeStyle,h=i.firstItem,m=n[1],y=(0,T["default"])({},this.props.style);f&&(y=(0,T["default"])(y,p));var g=(e={},(0,s["default"])(e,a,!!a),(0,s["default"])(e,l+"-item",!0),(0,s["default"])(e,l+"-item-disabled",d),(0,s["default"])(e,l+"-item-active",f),(0,s["default"])(e,l+"-item-fix-active-arrow",h&&f),e);return v["default"].createElement("div",(0,o["default"])({className:(0,b["default"])(g)},m,{style:y}),c?v["default"].createElement("span",{className:l+"-item-icon"},v["default"].createElement(C["default"],{type:c})):null,v["default"].createElement("span",{className:l+"-item-content"},r))},t}(v["default"].Component);E.defaultProps={prefixCls:"am-popover",disabled:!1},t["default"]=(0,N["default"])(E,"PopoverItem"),e.exports=t["default"]},[451,302],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){function i(){y&&(c["default"].unmountComponentAtNode(y),y.parentNode.removeChild(y),y=null),r(e)}var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(e){},o=(0,h["default"])({},{prefixCls:"am-popup",animationType:"slide-down"},t),a=o.prefixCls,s=o.transitionName,u=o.maskTransitionName,d=o.maskClosable,p=void 0===d||d,m=o.animationType,y=document.createElement("div");document.body.appendChild(y);var v="am-slide-down";return"slide-up"===m&&(v="am-slide-up"),c["default"].render(l["default"].createElement(f["default"],{prefixCls:a,visible:!0,title:"",footer:"",className:a+"-"+m,transitionName:s||v,maskTransitionName:u||"am-fade",onClose:i,maskClosable:p,wrapProps:o.wrapProps||{}},n),y),{instanceId:e,close:i}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(2),a=i(o),s=n(1),l=i(s),u=n(9),c=i(u),d=n(46),f=i(d),p=n(10),h=i(p),m={defaultInstance:null,instances:[]},y=1,v=function g(){(0,a["default"])(this,g)};t["default"]=v,v.newInstance=function(){var e=void 0;return{show:function(t,n){e=r(y++,n,t,function(e){for(var t=0;t<m.instances.length;t++)if(m.instances[t].instanceId===e)return void m.instances.splice(t,1)}),m.instances.push(e)},hide:function(){e.close()}}},v.show=function(e,t){m.defaultInstance=r("0",t,e,function(e){"0"===e&&(m.defaultInstance=null)})},v.hide=function(){m.defaultInstance.close()},e.exports=t["default"]},[451,303],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=n(10),v=i(y),g=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.percent,r=t.position,a=t.unfilled,s=t.style,l=void 0===s?{}:s,u={width:i+"%",height:0},c=(0,m["default"])((e={},(0,o["default"])(e,n+"-outer",!0),(0,o["default"])(e,n+"-fixed-outer","fixed"===r),(0,o["default"])(e,n+"-hide-outer","hide"===a),e));return p["default"].createElement("div",{className:c},p["default"].createElement("div",{className:n+"-bar",style:(0,v["default"])({},l,u)}))},t}(p["default"].Component);t["default"]=g,g.defaultProps={prefixCls:"am-progress",percent:0,position:"fixed",unfilled:"show"},e.exports=t["default"]},[451,304],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(7),a=i(o),s=n(6),l=i(s),u=n(2),c=i(u),d=n(4),f=i(d),p=n(3),h=i(p),m=n(1),y=i(m),v=n(5),g=i(v),b=n(26),M=i(b),T=n(51),x=i(T),C=n(38),_=i(C),w=M["default"].Item,S=function(e){function t(){return(0,c["default"])(this,t),(0,f["default"])(this,e.apply(this,arguments))}return(0,h["default"])(t,e),t.prototype.render=function(){var e,t=this,n=this.props,i=n.prefixCls,o=n.listPrefixCls,s=n.className,u=n.children,c=n.disabled,d=n.radioProps,f=void 0===d?{}:d,p=(0,g["default"])((e={},(0,l["default"])(e,i+"-item",!0),(0,l["default"])(e,i+"-item-disabled",c===!0),(0,l["default"])(e,s,s),e)),h=(0,_["default"])(this.props,["listPrefixCls","disabled","radioProps"]);c?delete h.onClick:h.onClick=h.onClick||r;var m={};return["name","defaultChecked","checked","onChange","disabled"].forEach(function(e){e in t.props&&(m[e]=t.props[e])}),y["default"].createElement(w,(0,a["default"])({},h,{prefixCls:o,className:p,extra:y["default"].createElement(x["default"],(0,a["default"])({},f,m))}),u)},t}(y["default"].Component);t["default"]=S,S.defaultProps={prefixCls:"am-radio",listPrefixCls:"am-list"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(51),o=i(r),a=n(179),s=i(a);o["default"].RadioItem=s["default"],t["default"]=o["default"],e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(72),s=i(a),l=n(13),u=i(l),c=n(10),d=i(c);s["default"].RefreshControl.defaultProps=(0,d["default"])({},s["default"].RefreshControl.defaultProps,{prefixCls:"am-refresh-control",icon:o["default"].createElement("div",{style:{lineHeight:"50px"}},o["default"].createElement("div",{className:"am-refresh-control-pull"},o["default"].createElement(u["default"],{type:"arrow-down"})," \u4e0b\u62c9"),o["default"].createElement("div",{className:"am-refresh-control-release"},o["default"].createElement(u["default"],{type:"arrow-up"})," \u91ca\u653e")),loading:o["default"].createElement("div",{style:{lineHeight:"50px"}},o["default"].createElement(u["default"],{type:"loading"})),refreshing:!1}),t["default"]=s["default"].RefreshControl,e.exports=t["default"]},[452,306],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),a=i(o),s=n(2),l=i(s),u=n(4),c=i(u),d=n(3),f=i(d),p=n(1),h=i(p),m=n(47),y=i(m),v=n(5),g=i(v),b=function(e){function t(){return(0,l["default"])(this,t),(0,c["default"])(this,e.apply(this,arguments))}return(0,f["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.imgUrl,r=t.title,o=t.message,s=t.buttonText,l=t.buttonClick,u=t.buttonType,c=t.className,d=(0,g["default"])((e={},(0,a["default"])(e,""+n,!0),(0,a["default"])(e,c,c),e));return h["default"].createElement("div",{className:d},h["default"].createElement("div",{className:n+"-pic",style:{backgroundImage:"url("+i+")"}}),""!==r?h["default"].createElement("div",{className:n+"-title"},r):null,""!==o?h["default"].createElement("div",{className:n+"-message"},o):null,""!==s?h["default"].createElement("div",{className:n+"-button"},h["default"].createElement(y["default"],{type:u,onClick:l},s)):null)},t}(h["default"].Component);t["default"]=b,b.defaultProps={prefixCls:"am-result",imgUrl:"",title:"",message:"",buttonText:"",buttonType:"",buttonClick:r},e.exports=t["default"]},function(e,t,n){"use strict";n(8),n(48),n(307)},function(e,t){"use strict";function n(){}Object.defineProperty(t,"__esModule",{value:!0});t.defaultProps={prefixCls:"am-search",placeholder:"",onSubmit:n,onChange:n,onFocus:n,onBlur:n,onClear:n,showCancelButton:!1,cancelText:"\u53d6\u6d88",disabled:!1}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=n(185),v=function(e){function t(n){(0,s["default"])(this,t);var i=(0,u["default"])(this,e.call(this,n));i.onSubmit=function(e){e.preventDefault(),i.props.onSubmit&&i.props.onSubmit(i.state.value)},i.onChange=function(e){var t=e.target.value;"value"in i.props||i.setState({value:t}),i.props.onChange&&i.props.onChange(t)},i.onFocus=function(){i.setState({focus:!0}),i.props.onFocus&&i.props.onFocus()},i.onBlur=function(){i.setState({focus:!1}),i.props.onBlur&&i.props.onBlur()},i.onClear=function(){"value"in i.props||i.setState({value:""}),i.refs.searchInput.focus(),i.props.onClear&&i.props.onClear(""),i.props.onChange&&i.props.onChange("")},i.onCancel=function(){i.props.onCancel?i.props.onCancel(i.state.value):i.onClear(),i.refs.searchInput.blur()};var r=void 0;return r="value"in n?n.value||"":"defaultValue"in n?n.defaultValue:"",i.state={value:r,focus:!1},i}return(0,d["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value})},t.prototype.componentDidMount=function(){/U3/i.test(navigator.userAgent)&&(this.initialInputContainerWidth=this.refs.searchInputContainer.offsetWidth,this.props.showCancelButton&&(this.refs.searchInputContainer.style.width=this.refs.searchInputContainer.offsetWidth-41*(window.devicePixelRatio||1)+"px"))},t.prototype.render=function(){var e,t,n,i=this.props,r=i.prefixCls,a=i.showCancelButton,s=i.disabled,l=i.placeholder,u=i.cancelText,c=i.className,d=this.state,f=d.value,h=d.focus,y=(0,m["default"])((e={},(0,o["default"])(e,""+r,!0),(0,o["default"])(e,r+"-start",a||h),(0,o["default"])(e,c,c),e)),v={};/U3/i.test(navigator.userAgent)&&this.initialInputContainerWidth&&(v=a||h?{width:this.initialInputContainerWidth-41*(window.devicePixelRatio||1)+"px"}:{width:this.initialInputContainerWidth+"px"});var g=(0,m["default"])((t={},(0,o["default"])(t,r+"-clear",!0),(0,o["default"])(t,r+"-clear-show",h&&f&&f.length>0),t)),b=(0,m["default"])((n={},(0,o["default"])(n,r+"-cancel",!0),(0,o["default"])(n,r+"-all-cancel",a),n));return p["default"].createElement("form",{onSubmit:this.onSubmit,className:y},p["default"].createElement("div",{ref:"searchInputContainer",className:r+"-input",style:v},p["default"].createElement("input",{type:"search",className:r+"-value",value:f,disabled:s,placeholder:l,onChange:this.onChange,onFocus:this.onFocus,onBlur:this.onBlur,ref:"searchInput"}),p["default"].createElement("a",{onClick:this.onClear,className:g})),p["default"].createElement("div",{className:b,onClick:this.onCancel},u))},t}(p["default"].Component);t["default"]=v,v.defaultProps=y.defaultProps,e.exports=t["default"]},[451,308],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(6),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(5),v=i(y),g=n(10),b=i(g),M=n(31),T=i(M),x=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t,n=this.props,i=n.label,r=n.prefixCls,a=n.selected,l=n.tintColor,u=n.enabled,c=n.touchFeedback,d=(0,b["default"])({},this.props);["prefixCls","label","selected","tintColor","enabled","touchFeedback","activeStyle"].forEach(function(e){d.hasOwnProperty(e)&&delete d[e]});var f=(0,v["default"])((e={},(0,s["default"])(e,r+"-item",!0),(0,s["default"])(e,r+"-item-selected",a),e)),p=(0,v["default"])((t={},(0,s["default"])(t,r+"-item-feedback",!0),(0,s["default"])(t,r+"-item-feedback-tintcolor",u&&c&&!a&&!l),t)),h=u&&c&&!a&&l?{backgroundColor:l}:{};return m["default"].createElement("div",(0,o["default"])({className:f,style:{color:a?"#fff":l,backgroundColor:a?l:"#fff",borderColor:l}},d),m["default"].createElement("div",{className:p,style:h}),i)},t}(m["default"].Component);x.defaultProps={onClick:function(){},selected:!1},t["default"]=(0,T["default"])(x),e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=n(188),v=i(y),g=function(e){function t(n){(0,s["default"])(this,t);var i=(0,u["default"])(this,e.call(this,n));return i.state={selectedIndex:n.selectedIndex},i}return(0,d["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){e.selectedIndex!==this.state.selectedIndex&&this.setState({selectedIndex:e.selectedIndex})},t.prototype.onClick=function(e,t,n){var i=this.props,r=i.enabled,o=i.onChange,a=i.onValueChange;r&&this.state.selectedIndex!==t&&(e.nativeEvent.selectedSegmentIndex=t,e.nativeEvent.value=n,o&&o(e),a&&a(n),this.setState({selectedIndex:t}))},t.prototype.render=function(){var e,t=this,n=this.props,i=n.prefixCls,r=n.style,a=n.enabled,s=n.values,l=void 0===s?[]:s,u=n.className,c=n.tintColor,d=this.state.selectedIndex,f=l.map(function(e,n){return p["default"].createElement(v["default"],{key:n,prefixCls:i,label:e,enabled:a,tintColor:c,selected:n===d,onClick:function(i){return t.onClick(i,n,e)}})}),h=(0,m["default"])((e={},(0,o["default"])(e,u,!!u),(0,o["default"])(e,""+i,!0),(0,o["default"])(e,i+"-disabled",!a),e));return p["default"].createElement("div",{className:h,style:r},f)},t}(p["default"].Component);t["default"]=g,g.defaultProps={prefixCls:"am-segment",selectedIndex:0,enabled:!0,values:[],onChange:function(){},onValueChange:function(){},style:{}},e.exports=t["default"]},[451,309],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(2),o=i(r),a=n(4),s=i(a),l=n(3),u=i(l),c=n(1),d=i(c),f=n(374),p=i(f),h=function(e){function t(){return(0,o["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){return d["default"].createElement("div",{className:this.props.prefixCls+"-wrapper"},d["default"].createElement(p["default"],this.props))},t}(d["default"].Component);t["default"]=h,h.defaultProps={prefixCls:"am-slider",tipTransitionName:"zoom-down"},e.exports=t["default"]},[451,310],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(6),s=i(a),l=n(14),u=i(l),c=n(2),d=i(c),f=n(4),p=i(f),h=n(3),m=i(h),y=n(1),v=i(y),g=n(5),b=i(g),M=n(15),T=i(M),x=n(362),C=i(x),_=function(e){function t(){return(0,d["default"])(this,t),(0,p["default"])(this,e.apply(this,arguments))}return(0,m["default"])(t,e),t.prototype.render=function(){var e,t=(0,T["default"])(this.props,["className","showNumber"]),n=(0,u["default"])(t,2),i=n[0],r=i.className,a=i.showNumber,l=n[1],c=(0,b["default"])((e={},(0,s["default"])(e,r,!!r),(0,s["default"])(e,"showNumber",!!a),e));return v["default"].createElement(C["default"],(0,o["default"])({},l,{ref:"inputNumber",className:c}))},t}(v["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-stepper",step:1,readOnly:!1,showNumber:!1,focusOnUpDown:!1},e.exports=t["default"]},[451,311],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){return"string"==typeof e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(7),a=i(o),s=n(2),l=i(s),u=n(4),c=i(u),d=n(3),f=i(d),p=n(1),h=i(p),m=n(378),y=i(m),v=n(13),g=i(v),b=function(e){ function t(){return(0,l["default"])(this,t),(0,c["default"])(this,e.apply(this,arguments))}return(0,f["default"])(t,e),t.prototype.render=function(){var e=this,t=this.props,n=t.current,i=t.direction;return h["default"].createElement(y["default"],(0,a["default"])({},this.props,{direction:i}),this.props.children.map(function(t,i){var o=-1;if(i<e.props.children.length-1){var a=e.props.children[i+1].props.status;"error"===a&&(o=i)}var s=o>-1?"error-tail":"",l=void 0,u=void 0;return t.props.icon?(l=t.props.icon,r(l)&&(u="",i>0&&i<=n?l="check-circle":"error"===t.props.status?l="cross-circle":"process"===t.props.status&&(l="check-circle"))):(u=i<=n?"":"ellipsis-item",l=i<=n?"check-circle-o":"error"===t.props.status?"cross-circle-o":"ellipsis-circle"),u=s+" "+u,h["default"].cloneElement(t,{key:i,icon:h["default"].createElement(g["default"],{type:l}),className:u})}))},t}(h["default"].Component);t["default"]=b,b.Step=y["default"].Step,b.defaultProps={prefixCls:"am-steps",iconPrefix:"ant",labelPlacement:"vertical",current:0,direction:"vertical"},e.exports=t["default"]},[452,312],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(6),o=i(r),a=n(53),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(380),v=i(y),g=n(71),b=i(g),M=n(5),T=i(M),x=n(81),C=i(x),_=function(e){function t(n){(0,u["default"])(this,t);var i=(0,d["default"])(this,e.call(this,n));return i.onLongTap=function(){var e=i.props,t=e.disabled,n=e.onOpen;t||(n&&n(),i.setState({showModal:!0}))},i.state={showModal:!1},i}return(0,p["default"])(t,e),t.prototype.onClose=function(){this.props.onClose&&this.props.onClose(),this.setState({showModal:!1})},t.prototype.renderAndroid=function(){var e=this,t=this.props,n=t.children,i=t.title,r=t.autoClose,o=t.left,a=void 0===o?[]:o,l=t.right,u=void 0===l?[]:l,c={recognizers:{press:{time:500,threshold:50}}},d=[].concat((0,s["default"])(a),(0,s["default"])(u)).map(function(t){var n=t.onPress||function(){};return{text:t.text,style:t.style,onPress:function(){n(),r&&e.onClose()}}});return m["default"].createElement("div",null,m["default"].createElement(b["default"],{onPress:this.onLongTap,options:c},n),this.state.showModal?m["default"].createElement(C["default"],{animated:!1,title:i,transparent:!0,closable:!1,maskClosable:!0,footer:d,visible:!0}):null)},t.prototype.render=function(){var e,t=this.props,n=t.className,i=t.prefixCls,r=t.left,a=void 0===r?[]:r,s=t.right,l=void 0===s?[]:s,u=t.autoClose,c=t.disabled,d=t.onOpen,f=t.onClose,p=t.children,h=!!navigator.userAgent.match(/Android/i),y=(0,T["default"])((e={},(0,o["default"])(e,""+i,1),(0,o["default"])(e,n,!!n),e));return a.length||l.length?m["default"].createElement("div",{className:y},h?this.renderAndroid():m["default"].createElement(v["default"],{prefixCls:i,left:a,right:l,autoClose:u,disabled:c,onOpen:d,onClose:f},p)):m["default"].createElement("div",{className:y},p)},t}(m["default"].Component);_.defaultProps={prefixCls:"am-swipe",title:"\u8bf7\u786e\u8ba4\u64cd\u4f5c",autoClose:!1,disabled:!1,left:[],right:[],onOpen:function(){},onClose:function(){}},t["default"]=_,e.exports=t["default"]},function(e,t,n){"use strict";n(8),n(82),n(314)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(6),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(5),v=i(y),g=function(e){function t(){(0,u["default"])(this,t);var n=(0,d["default"])(this,e.apply(this,arguments));return n.onChange=function(e){var t=e.target.checked;n.props.onChange&&n.props.onChange(t)},n}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.style,r=t.name,a=t.checked,l=t.disabled,u=t.className,c=t.onTintColor,d=(0,v["default"])((e={},(0,s["default"])(e,""+n,!0),(0,s["default"])(e,u,u),e)),f=c?{backgroundColor:c}:{};return m["default"].createElement("label",{className:d,style:i},m["default"].createElement("input",(0,o["default"])({type:"checkbox",name:r,className:n+"-checkbox"},l?{disabled:"disabled"}:"",{checked:a,onChange:this.onChange})),m["default"].createElement("div",{className:"checkbox",style:f}))},t}(m["default"].Component);t["default"]=g,g.defaultProps={prefixCls:"am-switch",name:"",checked:!1,disabled:!1,onChange:function(){}},e.exports=t["default"]},[451,315],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(2),o=i(r),a=n(4),s=i(a),l=n(3),u=i(l),c=n(1),d=i(c),f=n(75),p=i(f),h=function(e){function t(){return(0,o["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){var e=this.props,t=e.title,n=e.icon,i=e.selectedIcon,r=e.prefixCls,o=e.badge,a=e.selected,s=e.unselectedTintColor,l=e.tintColor,u=a?i:n,c=d["default"].isValidElement(u)?u:d["default"].createElement("img",{className:r+"-image",src:u.uri||u,alt:t}),f=a?l:s;return d["default"].createElement("div",this.props.dataAttrs,d["default"].createElement("div",{className:r+"-icon",style:{color:f}},o?d["default"].createElement(p["default"],{text:o,className:r+"-badge"},c):c),d["default"].createElement("p",{className:r+"-title",style:{color:a?l:s}},t))},t}(d["default"].Component);t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(112),s=i(a),l=n(201),u=i(l),c=n(69),d=i(c),f=n(392),p=i(f),h=n(25),m=i(h),y=o["default"].createClass({displayName:"AntTabBar",statics:{Item:function(){}},getDefaultProps:function(){return{prefixCls:"am-tab-bar",barTintColor:"white",tintColor:"#108ee9",unselectedTintColor:"#888"}},onChange:function(e){o["default"].Children.forEach(this.props.children,function(t){t.key===e&&t.props.onPress&&t.props.onPress()})},renderTabBar:function(){var e=this.props,t=e.onTabClick,n=e.barTintColor,i=e.hidden,r=e.prefixCls,a=i?r+"-bar-hidden":"";return o["default"].createElement(p["default"],{className:a,onTabClick:t,style:{backgroundColor:n}})},renderTabContent:function(){return o["default"].createElement(d["default"],{animated:!1})},render:function(){var e=this,t=void 0,n=[];o["default"].Children.forEach(this.props.children,function(e){e.props.selected&&(t=e.key),n.push(e)});var i=this.props,r=i.tintColor,l=i.unselectedTintColor,c=n.map(function(t){var n=t.props,i=o["default"].createElement(u["default"],{prefixCls:e.props.prefixCls+"-tab",badge:n.badge,selected:n.selected,icon:n.icon,selectedIcon:n.selectedIcon,title:n.title,tintColor:r,unselectedTintColor:l,dataAttrs:(0,m["default"])(n)});return o["default"].createElement(a.TabPane,{placeholder:"\u6b63\u5728\u52a0\u8f7d",tab:i,key:t.key},n.children)});return o["default"].createElement(s["default"],{renderTabBar:this.renderTabBar,renderTabContent:this.renderTabContent,tabBarPosition:"bottom",prefixCls:this.props.prefixCls,activeKey:t,onChange:this.onChange},c)}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";n(8),n(316),n(76)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(10),m=i(h),y=n(385),v=i(y),g=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e=this.props,t=e.columns,n=e.dataSource,i=e.direction,r=e.scrollX,a=e.titleFixed,s=this.props,l=s.style,u=s.className,c=(0,m["default"])({},this.props);["style","className"].forEach(function(e){c.hasOwnProperty(e)&&delete c[e]});var d=void 0;return i&&"vertical"!==i?"horizon"===i?(t[0].className="am-table-horizonTitle",d=p["default"].createElement(v["default"],(0,o["default"])({},c,{columns:t,data:n,className:"am-table",showHeader:!1,scroll:{x:r}}))):"mix"===i&&(t[0].className="am-table-horizonTitle",d=p["default"].createElement(v["default"],(0,o["default"])({},c,{columns:t,data:n,className:"am-table",scroll:{x:r}}))):d=a?p["default"].createElement(v["default"],(0,o["default"])({},c,{columns:t,data:n,className:"am-table",scroll:{x:!0},showHeader:!1})):p["default"].createElement(v["default"],(0,o["default"])({},c,{columns:t,data:n,className:"am-table",scroll:{x:r}})),p["default"].createElement("div",{className:u,style:l},d)},t}(p["default"].Component);t["default"]=g,g.defaultProps={dataSource:[],prefixCls:"am-table"},e.exports=t["default"]},[451,317],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(1),s=i(a),l=n(112),u=i(l),c=n(391),d=i(c),f=n(69),p=i(f),h=n(388),m=i(h),y=s["default"].createClass({displayName:"Tabs",statics:{TabPane:l.TabPane},getDefaultProps:function(){return{prefixCls:"am-tabs",animated:!0,swipeable:!0,onChange:function(){},tabBarPosition:"top",onTabClick:function(){}}},renderTabBar:function(){var e=this.props;return s["default"].createElement(m["default"],{onTabClick:e.onTabClick,inkBarAnimated:e.animated})},renderTabContent:function(){var e=this.props,t=e.animated,n=e.swipeable;return n?s["default"].createElement(d["default"],{animated:t}):s["default"].createElement(p["default"],{animated:t})},render:function(){return s["default"].createElement(u["default"],(0,o["default"])({renderTabBar:this.renderTabBar,renderTabContent:this.renderTabContent},this.props))}});t["default"]=y,e.exports=t["default"]},[451,318],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(7),o=i(r),a=n(6),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(5),v=i(y),g=n(13),b=i(g),M=n(25),T=i(M),x=function(e){function t(n){(0,u["default"])(this,t);var i=(0,d["default"])(this,e.call(this,n));return i.onClick=function(){var e=i.props,t=e.disabled,n=e.onChange;if(!t){var r=i.state.selected;i.setState({selected:!r},function(){n&&n(!r)})}},i.onTagClose=function(){i.props.onClose&&i.props.onClose(),i.setState({closed:!0},i.props.afterClose)},i.state={selected:n.selected,closed:!1},i}return(0,p["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){this.props.selected!==e.selected&&this.setState({selected:e.selected})},t.prototype.render=function(){var e,t=this.props,n=t.children,i=t.className,r=t.prefixCls,a=t.disabled,l=t.closable,u=t.small,c=t.style,d=(0,v["default"])((e={},(0,s["default"])(e,i,!!i),(0,s["default"])(e,""+r,!0),(0,s["default"])(e,r+"-normal",!a&&(!this.state.selected||u||l)),(0,s["default"])(e,r+"-small",u),(0,s["default"])(e,r+"-active",this.state.selected&&!a&&!u&&!l),(0,s["default"])(e,r+"-disabled",a),(0,s["default"])(e,r+"-closable",l),e));return this.state.closed?null:m["default"].createElement("div",(0,o["default"])({},(0,T["default"])(this.props),{className:d,onClick:this.onClick,style:c}),m["default"].createElement("div",{className:r+"-text"},n),l&&!a&&!u&&m["default"].createElement("div",{className:r+"-close",onClick:this.onTagClose},m["default"].createElement(b["default"],{type:"cross-circle",size:"xs"})))},t}(m["default"].Component);t["default"]=x,x.defaultProps={prefixCls:"am-tag",disabled:!1,selected:!1,closable:!1,small:!1,onChange:function(){},onClose:function(){},afterClose:function(){}},e.exports=t["default"]},[452,319],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(2),o=i(r),a=n(4),s=i(a),l=n(3),u=i(l),c=n(1),d=i(c),f=n(87),p=i(f),h=function(e){function t(){return(0,o["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){return d["default"].createElement(p["default"],this.props)},t}(d["default"].Component);t["default"]=h,h.defaultProps={Component:"span"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}function o(e){return"undefined"==typeof e||null===e?"":e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var a=n(7),s=i(a),l=n(6),u=i(l),c=n(2),d=i(c),f=n(4),p=i(f),h=n(3),m=i(h),y=n(1),v=i(y),g=n(5),b=i(g),M=n(38),T=i(M),x=function(e){function t(n){(0,d["default"])(this,t);var i=(0,p["default"])(this,e.call(this,n));return i.onChange=function(e){var t=e.target.value,n=i.props.onChange;if(n&&n(t),i.props.autoHeight){var r=i.refs.textarea;r.style.height="",r.style.height=r.scrollHeight+"px"}},i.onBlur=function(e){i.debounceTimeout=setTimeout(function(){i.setState({focus:!1})},500);var t=e.target.value;i.props.onBlur&&i.props.onBlur(t)},i.onFocus=function(e){i.setState({focus:!0});var t=e.target.value;i.props.onFocus&&i.props.onFocus(t)},i.onErrorClick=function(){i.props.onErrorClick&&i.props.onErrorClick()},i.clearInput=function(){i.props.onChange&&i.props.onChange("")},i.state={focus:!1},i}return(0,m["default"])(t,e),t.prototype.shouldComponentUpdate=function(e,t){return e.value!==this.props.value||e.defaultValue!==this.props.defaultValue||e.error!==this.props.error||e.disabled!==this.props.disabled||e.editable!==this.props.editable||t.focus!==this.state.focus},t.prototype.componentWillUnmount=function(){this.debounceTimeout&&clearTimeout(this.debounceTimeout)},t.prototype.render=function(){var e,t,n=this.props,i=n.prefixCls,r=n.prefixListCls,a=n.style,l=n.title,c=n.name,d=n.value,f=n.defaultValue,p=n.placeholder,h=n.clear,m=n.rows,y=n.count,g=n.editable,M=n.disabled,x=n.error,C=n.className,_=n.labelNumber,w=n.autoHeight,S=(0,T["default"])(this.props,["prefixCls","prefixListCls","editable","style","clear","children","error","className","count","labelNumber","title","onErrorClick","autoHeight"]),N=void 0;N="value"in this.props?{value:o(d)}:{defaultValue:f};var E=this.state.focus,P=(0,b["default"])((e={},(0,u["default"])(e,r+"-item",!0),(0,u["default"])(e,i+"-item",!0),(0,u["default"])(e,i+"-disabled",M),(0,u["default"])(e,i+"-item-single-line",1===m&&!w),(0,u["default"])(e,i+"-error",x),(0,u["default"])(e,i+"-focus",E),(0,u["default"])(e,C,C),e)),D=(0,b["default"])((t={},(0,u["default"])(t,i+"-label",!0),(0,u["default"])(t,i+"-label-2",2===_),(0,u["default"])(t,i+"-label-3",3===_),(0,u["default"])(t,i+"-label-4",4===_),(0,u["default"])(t,i+"-label-5",5===_),(0,u["default"])(t,i+"-label-6",6===_),(0,u["default"])(t,i+"-label-7",7===_),t));return v["default"].createElement("div",{className:P,style:a},l?v["default"].createElement("div",{className:D},l):null,v["default"].createElement("div",{className:i+"-control"},v["default"].createElement("textarea",(0,s["default"])({},S,N,{ref:"textarea",name:c,rows:m,placeholder:p,maxLength:y,onChange:this.onChange,onBlur:this.onBlur,onFocus:this.onFocus,readOnly:!g,disabled:M}))),h&&g&&d&&d.length>0?v["default"].createElement("div",{className:i+"-clear",onClick:this.clearInput,onTouchStart:this.clearInput}):null,x?v["default"].createElement("div",{className:i+"-error-extra",onClick:this.onErrorClick}):null,y>0&&m>1?v["default"].createElement("span",{className:i+"-count"},v["default"].createElement("span",null,d&&d.length),"/",y):null)},t}(v["default"].Component);t["default"]=x,x.defaultProps={prefixCls:"am-textarea",prefixListCls:"am-list",title:"",autoHeight:!1,editable:!0,disabled:!1,placeholder:"",clear:!1,rows:1,onChange:r,onBlur:r,onFocus:r,onErrorClick:r,error:!1,labelNumber:4},e.exports=t["default"]},[453,320],function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(5),m=i(h),y=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,i=t.size,r=t.className,a=t.style,s=t.onClick,l=(0,m["default"])((e={},(0,o["default"])(e,""+n,!0),(0,o["default"])(e,n+"-"+i,!0),(0,o["default"])(e,r,!!r),e));return p["default"].createElement("div",{className:l,style:a,onClick:s})},t}(p["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"am-whitespace",size:"md"},e.exports=t["default"]},[451,322],function(e,t,n){e.exports={"default":n(226),__esModule:!0}},function(e,t,n){e.exports={"default":n(227),__esModule:!0}},function(e,t,n){e.exports={"default":n(228),__esModule:!0}},function(e,t,n){e.exports={"default":n(229),__esModule:!0}},function(e,t,n){e.exports={"default":n(230),__esModule:!0}},function(e,t,n){e.exports={"default":n(231),__esModule:!0}},function(e,t,n){e.exports={"default":n(232),__esModule:!0}},function(e,t,n){e.exports={"default":n(233),__esModule:!0}},function(e,t,n){e.exports={"default":n(234),__esModule:!0}},function(e,t,n){e.exports={"default":n(235),__esModule:!0}},function(e,t,n){function i(e){if(!e||!e.nodeType)throw new Error("A DOM element reference is required");this.el=e,this.list=e.classList}try{var r=n(90)}catch(o){var r=n(90)}var a=/\s+/,s=Object.prototype.toString;e.exports=function(e){return new i(e)},i.prototype.add=function(e){if(this.list)return this.list.add(e),this;var t=this.array(),n=r(t,e);return~n||t.push(e),this.el.className=t.join(" "),this},i.prototype.remove=function(e){if("[object RegExp]"==s.call(e))return this.removeMatching(e);if(this.list)return this.list.remove(e),this;var t=this.array(),n=r(t,e);return~n&&t.splice(n,1),this.el.className=t.join(" "),this},i.prototype.removeMatching=function(e){for(var t=this.array(),n=0;n<t.length;n++)e.test(t[n])&&this.remove(t[n]);return this},i.prototype.toggle=function(e,t){return this.list?("undefined"!=typeof t?t!==this.list.toggle(e,t)&&this.list.toggle(e):this.list.toggle(e),this):("undefined"!=typeof t?t?this.add(e):this.remove(e):this.has(e)?this.remove(e):this.add(e),this)},i.prototype.array=function(){var e=this.el.getAttribute("class")||"",t=e.replace(/^\s+|\s+$/g,""),n=t.split(a);return""===n[0]&&n.shift(),n},i.prototype.has=i.prototype.contains=function(e){return this.list?this.list.contains(e):!!~r(this.array(),e)}},function(e,t,n){n(44),n(260),e.exports=n(11).Array.from},function(e,t,n){n(68),n(44),e.exports=n(258)},function(e,t,n){n(68),n(44),e.exports=n(259)},function(e,t,n){n(262),e.exports=n(11).Object.assign},function(e,t,n){n(263);var i=n(11).Object;e.exports=function(e,t){return i.create(e,t)}},function(e,t,n){n(264);var i=n(11).Object;e.exports=function(e,t,n){return i.defineProperty(e,t,n)}},function(e,t,n){n(265),e.exports=n(11).Object.keys},function(e,t,n){n(266),e.exports=n(11).Object.setPrototypeOf},function(e,t,n){n(268),n(267),n(269),n(270),e.exports=n(11).Symbol},function(e,t,n){n(44),n(68),e.exports=n(67).f("iterator")},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){e.exports=function(){}},function(e,t,n){var i=n(24),r=n(100),o=n(257);e.exports=function(e){return function(t,n,a){var s,l=i(t),u=r(l.length),c=o(a,u);if(e&&n!=n){for(;u>c;)if(s=l[c++],s!=s)return!0}else for(;u>c;c++)if((e||c in l)&&l[c]===n)return e||c||0;return!e&&-1}}},function(e,t,n){"use strict";var i=n(19),r=n(36);e.exports=function(e,t,n){t in e?i.f(e,t,r(0,n)):e[t]=n}},function(e,t,n){var i=n(30),r=n(60),o=n(41);e.exports=function(e){var t=i(e),n=r.f;if(n)for(var a,s=n(e),l=o.f,u=0;s.length>u;)l.call(e,a=s[u++])&&t.push(a);return t}},function(e,t,n){e.exports=n(18).document&&document.documentElement},function(e,t,n){var i=n(29),r=n(12)("iterator"),o=Array.prototype;e.exports=function(e){return void 0!==e&&(i.Array===e||o[r]===e)}},function(e,t,n){var i=n(54);e.exports=Array.isArray||function(e){return"Array"==i(e)}},function(e,t,n){var i=n(21);e.exports=function(e,t,n,r){try{return r?t(i(n)[0],n[1]):t(n)}catch(o){var a=e["return"];throw void 0!==a&&i(a.call(e)),o}}},function(e,t,n){"use strict";var i=n(59),r=n(36),o=n(61),a={};n(28)(a,n(12)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=i(a,{next:r(1,n)}),o(e,t+" Iterator")}},function(e,t,n){var i=n(12)("iterator"),r=!1;try{var o=[7][i]();o["return"]=function(){r=!0},Array.from(o,function(){throw 2})}catch(a){}e.exports=function(e,t){if(!t&&!r)return!1;var n=!1;try{var o=[7],a=o[i]();a.next=function(){return{done:n=!0}},o[i]=function(){return a},e(o)}catch(s){}return n}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var i=n(30),r=n(24);e.exports=function(e,t){for(var n,o=r(e),a=i(o),s=a.length,l=0;s>l;)if(o[n=a[l++]]===t)return n}},function(e,t,n){var i=n(43)("meta"),r=n(35),o=n(23),a=n(19).f,s=0,l=Object.isExtensible||function(){return!0},u=!n(27)(function(){return l(Object.preventExtensions({}))}),c=function(e){a(e,i,{value:{i:"O"+ ++s,w:{}}})},d=function(e,t){if(!r(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!o(e,i)){if(!l(e))return"F";if(!t)return"E";c(e)}return e[i].i},f=function(e,t){if(!o(e,i)){if(!l(e))return!0;if(!t)return!1;c(e)}return e[i].w},p=function(e){return u&&h.NEED&&l(e)&&!o(e,i)&&c(e),e},h=e.exports={KEY:i,NEED:!1,fastKey:d,getWeak:f,onFreeze:p}},function(e,t,n){"use strict";var i=n(30),r=n(60),o=n(41),a=n(42),s=n(94),l=Object.assign;e.exports=!l||n(27)(function(){var e={},t={},n=Symbol(),i="abcdefghijklmnopqrst";return e[n]=7,i.split("").forEach(function(e){t[e]=e}),7!=l({},e)[n]||Object.keys(l({},t)).join("")!=i})?function(e,t){for(var n=a(e),l=arguments.length,u=1,c=r.f,d=o.f;l>u;)for(var f,p=s(arguments[u++]),h=c?i(p).concat(c(p)):i(p),m=h.length,y=0;m>y;)d.call(p,f=h[y++])&&(n[f]=p[f]);return n}:l},function(e,t,n){var i=n(19),r=n(21),o=n(30);e.exports=n(22)?Object.defineProperties:function(e,t){r(e);for(var n,a=o(t),s=a.length,l=0;s>l;)i.f(e,n=a[l++],t[n]);return e}},function(e,t,n){var i=n(24),r=n(97).f,o={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],s=function(e){try{return r(e)}catch(t){return a.slice()}};e.exports.f=function(e){return a&&"[object Window]"==o.call(e)?s(e):r(i(e))}},function(e,t,n){var i=n(23),r=n(42),o=n(62)("IE_PROTO"),a=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=r(e),i(e,o)?e[o]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},function(e,t,n){var i=n(17),r=n(11),o=n(27);e.exports=function(e,t){var n=(r.Object||{})[e]||Object[e],a={};a[e]=t(n),i(i.S+i.F*o(function(){n(1)}),"Object",a)}},function(e,t,n){var i=n(35),r=n(21),o=function(e,t){if(r(e),!i(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,i){try{i=n(55)(Function.call,n(96).f(Object.prototype,"__proto__").set,2),i(e,[]),t=!(e instanceof Array)}catch(r){t=!0}return function(e,n){return o(e,n),t?e.__proto__=n:i(e,n),e}}({},!1):void 0),check:o}},function(e,t,n){var i=n(64),r=n(56);e.exports=function(e){return function(t,n){var o,a,s=String(r(t)),l=i(n),u=s.length;return l<0||l>=u?e?"":void 0:(o=s.charCodeAt(l),o<55296||o>56319||l+1===u||(a=s.charCodeAt(l+1))<56320||a>57343?e?s.charAt(l):o:e?s.slice(l,l+2):(o-55296<<10)+(a-56320)+65536)}}},function(e,t,n){var i=n(64),r=Math.max,o=Math.min;e.exports=function(e,t){return e=i(e),e<0?r(e+t,0):o(e,t)}},function(e,t,n){var i=n(21),r=n(101);e.exports=n(11).getIterator=function(e){var t=r(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return i(t.call(e))}},function(e,t,n){var i=n(91),r=n(12)("iterator"),o=n(29);e.exports=n(11).isIterable=function(e){var t=Object(e);return void 0!==t[r]||"@@iterator"in t||o.hasOwnProperty(i(t))}},function(e,t,n){"use strict";var i=n(55),r=n(17),o=n(42),a=n(244),s=n(242),l=n(100),u=n(239),c=n(101);r(r.S+r.F*!n(246)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,r,d,f=o(e),p="function"==typeof this?this:Array,h=arguments.length,m=h>1?arguments[1]:void 0,y=void 0!==m,v=0,g=c(f);if(y&&(m=i(m,h>2?arguments[2]:void 0,2)),void 0==g||p==Array&&s(g))for(t=l(f.length),n=new p(t);t>v;v++)u(n,v,y?m(f[v],v):f[v]);else for(d=g.call(f),n=new p;!(r=d.next()).done;v++)u(n,v,y?a(d,m,[r.value,v],!0):r.value);return n.length=v,n}})},function(e,t,n){"use strict";var i=n(237),r=n(247),o=n(29),a=n(24);e.exports=n(95)(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,r(1)):"keys"==t?r(0,n):"values"==t?r(0,e[n]):r(0,[n,e[n]])},"values"),o.Arguments=o.Array,i("keys"),i("values"),i("entries")},function(e,t,n){var i=n(17);i(i.S+i.F,"Object",{assign:n(250)})},function(e,t,n){var i=n(17);i(i.S,"Object",{create:n(59)})},function(e,t,n){var i=n(17);i(i.S+i.F*!n(22),"Object",{defineProperty:n(19).f})},function(e,t,n){var i=n(42),r=n(30);n(254)("keys",function(){return function(e){return r(i(e))}})},function(e,t,n){var i=n(17);i(i.S,"Object",{setPrototypeOf:n(255).set})},function(e,t){},function(e,t,n){"use strict";var i=n(18),r=n(23),o=n(22),a=n(17),s=n(99),l=n(249).KEY,u=n(27),c=n(63),d=n(61),f=n(43),p=n(12),h=n(67),m=n(66),y=n(248),v=n(240),g=n(243),b=n(21),M=n(24),T=n(65),x=n(36),C=n(59),_=n(252),w=n(96),S=n(19),N=n(30),E=w.f,P=S.f,D=_.f,I=i.Symbol,L=i.JSON,j=L&&L.stringify,k="prototype",O=p("_hidden"),A=p("toPrimitive"),z={}.propertyIsEnumerable,R=c("symbol-registry"),W=c("symbols"),Y=c("op-symbols"),H=Object[k],B="function"==typeof I,U=i.QObject,F=!U||!U[k]||!U[k].findChild,V=o&&u(function(){return 7!=C(P({},"a",{get:function(){return P(this,"a",{value:7}).a}})).a})?function(e,t,n){var i=E(H,t);i&&delete H[t],P(e,t,n),i&&e!==H&&P(H,t,i)}:P,Q=function(e){var t=W[e]=C(I[k]);return t._k=e,t},G=B&&"symbol"==typeof I.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof I},Z=function(e,t,n){return e===H&&Z(Y,t,n),b(e),t=T(t,!0),b(n),r(W,t)?(n.enumerable?(r(e,O)&&e[O][t]&&(e[O][t]=!1),n=C(n,{enumerable:x(0,!1)})):(r(e,O)||P(e,O,x(1,{})),e[O][t]=!0),V(e,t,n)):P(e,t,n)},X=function(e,t){b(e);for(var n,i=v(t=M(t)),r=0,o=i.length;o>r;)Z(e,n=i[r++],t[n]);return e},J=function(e,t){return void 0===t?C(e):X(C(e),t)},K=function(e){var t=z.call(this,e=T(e,!0));return!(this===H&&r(W,e)&&!r(Y,e))&&(!(t||!r(this,e)||!r(W,e)||r(this,O)&&this[O][e])||t)},q=function(e,t){if(e=M(e),t=T(t,!0),e!==H||!r(W,t)||r(Y,t)){var n=E(e,t);return!n||!r(W,t)||r(e,O)&&e[O][t]||(n.enumerable=!0),n}},$=function(e){for(var t,n=D(M(e)),i=[],o=0;n.length>o;)r(W,t=n[o++])||t==O||t==l||i.push(t);return i},ee=function(e){for(var t,n=e===H,i=D(n?Y:M(e)),o=[],a=0;i.length>a;)!r(W,t=i[a++])||n&&!r(H,t)||o.push(W[t]);return o};B||(I=function(){if(this instanceof I)throw TypeError("Symbol is not a constructor!");var e=f(arguments.length>0?arguments[0]:void 0),t=function(n){this===H&&t.call(Y,n),r(this,O)&&r(this[O],e)&&(this[O][e]=!1),V(this,e,x(1,n))};return o&&F&&V(H,e,{configurable:!0,set:t}),Q(e)},s(I[k],"toString",function(){return this._k}),w.f=q,S.f=Z,n(97).f=_.f=$,n(41).f=K,n(60).f=ee,o&&!n(58)&&s(H,"propertyIsEnumerable",K,!0),h.f=function(e){return Q(p(e))}),a(a.G+a.W+a.F*!B,{Symbol:I});for(var te="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ne=0;te.length>ne;)p(te[ne++]);for(var te=N(p.store),ne=0;te.length>ne;)m(te[ne++]);a(a.S+a.F*!B,"Symbol",{"for":function(e){return r(R,e+="")?R[e]:R[e]=I(e)},keyFor:function(e){if(G(e))return y(R,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){F=!0},useSimple:function(){F=!1}}),a(a.S+a.F*!B,"Object",{create:J,defineProperty:Z,defineProperties:X,getOwnPropertyDescriptor:q,getOwnPropertyNames:$,getOwnPropertySymbols:ee}),L&&a(a.S+a.F*(!B||u(function(){var e=I();return"[null]"!=j([e])||"{}"!=j({a:e})||"{}"!=j(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!G(e)){for(var t,n,i=[e],r=1;arguments.length>r;)i.push(arguments[r++]);return t=i[1],"function"==typeof t&&(n=t),!n&&g(t)||(t=function(e,t){if(n&&(t=n.call(this,e,t)),!G(t))return t}),i[1]=t,j.apply(L,i)}}}),I[k][A]||n(28)(I[k],A,I[k].valueOf),d(I,"Symbol"),d(Math,"Math",!0),d(i.JSON,"JSON",!0)},function(e,t,n){n(66)("asyncIterator")},function(e,t,n){n(66)("observable")},function(e,t){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete o.animationend.animation,"TransitionEvent"in window||delete o.transitionend.transition;for(var n in o)if(o.hasOwnProperty(n)){var i=o[n];for(var r in i)if(r in t){a.push(i[r]);break}}}function i(e,t,n){e.addEventListener(t,n,!1)}function r(e,t,n){e.removeEventListener(t,n,!1)}Object.defineProperty(t,"__esModule",{value:!0});var o={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},a=[];"undefined"!=typeof window&&"undefined"!=typeof document&&n();var s={addEndEventListener:function(e,t){return 0===a.length?void window.setTimeout(t,0):void a.forEach(function(n){i(e,n,t)})},endEvents:a,removeEndEventListener:function(e,t){0!==a.length&&a.forEach(function(n){r(e,n,t)})}};t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n,i){var r=a["default"].clone(e),o={width:t.width,height:t.height};return i.adjustX&&r.left<n.left&&(r.left=n.left),i.resizeWidth&&r.left>=n.left&&r.left+o.width>n.right&&(o.width-=r.left+o.width-n.right),i.adjustX&&r.left+o.width>n.right&&(r.left=Math.max(n.right-o.width,n.left)),i.adjustY&&r.top<n.top&&(r.top=n.top),i.resizeHeight&&r.top>=n.top&&r.top+o.height>n.bottom&&(o.height-=r.top+o.height-n.bottom),i.adjustY&&r.top+o.height>n.bottom&&(r.top=Math.max(n.bottom-o.height,n.top)),a["default"].mix(r,o)}Object.defineProperty(t,"__esModule",{value:!0});var o=n(37),a=i(o);t["default"]=r,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=t.charAt(0),i=t.charAt(1),r=e.width,o=e.height,a=void 0,s=void 0;return a=e.left,s=e.top,"c"===n?s+=o/2:"b"===n&&(s+=o),"c"===i?a+=r/2:"r"===i&&(a+=r),{left:a,top:s}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n,i,r){var o=void 0,s=void 0,l=void 0,u=void 0;return o={left:e.left,top:e.top},l=(0,a["default"])(t,n[1]),u=(0,a["default"])(e,n[0]),s=[u.left-l.left,u.top-l.top],{left:o.left-s[0]+i[0]-r[0],top:o.top-s[1]+i[1]-r[1]}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(273),a=i(o);t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=void 0,n=void 0,i=void 0;if(a["default"].isWindow(e)||9===e.nodeType){var r=a["default"].getWindow(e);t={left:a["default"].getWindowScrollLeft(r),top:a["default"].getWindowScrollTop(r)},n=a["default"].viewportWidth(r),i=a["default"].viewportHeight(r)}else t=a["default"].offset(e),n=a["default"].outerWidth(e),i=a["default"].outerHeight(e);return t.width=n,t.height=i,t}Object.defineProperty(t,"__esModule",{value:!0});var o=n(37),a=i(o);t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){for(var t={left:0,right:1/0,top:0,bottom:1/0},n=(0,l["default"])(e),i=void 0,r=void 0,o=void 0,s=e.ownerDocument,u=s.defaultView||s.parentWindow,c=s.body,d=s.documentElement;n;){if(navigator.userAgent.indexOf("MSIE")!==-1&&0===n.clientWidth||n===c||n===d||"visible"===a["default"].css(n,"overflow")){if(n===c||n===d)break}else{var f=a["default"].offset(n);f.left+=n.clientLeft,f.top+=n.clientTop,t.top=Math.max(t.top,f.top),t.right=Math.min(t.right,f.left+n.clientWidth), t.bottom=Math.min(t.bottom,f.top+n.clientHeight),t.left=Math.max(t.left,f.left)}n=(0,l["default"])(n)}return i=a["default"].getWindowScrollLeft(u),r=a["default"].getWindowScrollTop(u),t.left=Math.max(t.left,i),t.top=Math.max(t.top,r),o={width:a["default"].viewportWidth(u),height:a["default"].viewportHeight(u)},t.right=Math.min(t.right,i+o.width),t.bottom=Math.min(t.bottom,r+o.height),t.top>=0&&t.left>=0&&t.bottom>t.top&&t.right>t.left?t:null}Object.defineProperty(t,"__esModule",{value:!0});var o=n(37),a=i(o),s=n(103),l=i(s);t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return e.left<n.left||e.left+t.width>n.right}function o(e,t,n){return e.top<n.top||e.top+t.height>n.bottom}function a(e,t,n){return e.left>n.right||e.left+t.width<n.left}function s(e,t,n){return e.top>n.bottom||e.top+t.height<n.top}function l(e,t,n){var i=[];return h["default"].each(e,function(e){i.push(e.replace(t,function(e){return n[e]}))}),i}function u(e,t){return e[t]=-e[t],e}function c(e,t){var n=void 0;return n=/%$/.test(e)?parseInt(e.substring(0,e.length-1),10)/100*t:parseInt(e,10),n||0}function d(e,t){e[0]=c(e[0],t.width),e[1]=c(e[1],t.height)}function f(e,t,n){var i=n.points,c=n.offset||[0,0],f=n.targetOffset||[0,0],p=n.overflow,m=n.target||t,y=n.source||e;c=[].concat(c),f=[].concat(f),p=p||{};var v={},b=0,T=(0,g["default"])(y),C=(0,x["default"])(y),w=(0,x["default"])(m);d(c,C),d(f,w);var S=(0,_["default"])(C,w,i,c,f),N=h["default"].merge(C,S);if(T&&(p.adjustX||p.adjustY)){if(p.adjustX&&r(S,C,T)){var E=l(i,/[lr]/gi,{l:"r",r:"l"}),P=u(c,0),D=u(f,0),I=(0,_["default"])(C,w,E,P,D);a(I,C,T)||(b=1,i=E,c=P,f=D)}if(p.adjustY&&o(S,C,T)){var L=l(i,/[tb]/gi,{t:"b",b:"t"}),j=u(c,1),k=u(f,1),O=(0,_["default"])(C,w,L,j,k);s(O,C,T)||(b=1,i=L,c=j,f=k)}b&&(S=(0,_["default"])(C,w,i,c,f),h["default"].mix(N,S)),v.adjustX=p.adjustX&&r(S,C,T),v.adjustY=p.adjustY&&o(S,C,T),(v.adjustX||v.adjustY)&&(N=(0,M["default"])(S,C,T,v))}return N.width!==C.width&&h["default"].css(y,"width",h["default"].width(y)+N.width-C.width),N.height!==C.height&&h["default"].css(y,"height",h["default"].height(y)+N.height-C.height),h["default"].offset(y,{left:N.left,top:N.top},{useCssRight:n.useCssRight,useCssBottom:n.useCssBottom,useCssTransform:n.useCssTransform}),{points:i,offset:c,targetOffset:f,overflow:v}}Object.defineProperty(t,"__esModule",{value:!0});var p=n(37),h=i(p),m=n(103),y=i(m),v=n(276),g=i(v),b=n(272),M=i(b),T=n(275),x=i(T),C=n(274),_=i(C);f.__getOffsetParent=y["default"],f.__getVisibleRectForElement=g["default"],t["default"]=f,e.exports=t["default"]},function(e,t){"use strict";function n(){if(void 0!==c)return c;c="";var e=document.createElement("p").style,t="Transform";for(var n in d)n+t in e&&(c=n);return c}function i(){return n()?n()+"TransitionProperty":"transitionProperty"}function r(){return n()?n()+"Transform":"transform"}function o(e,t){var n=i();n&&(e.style[n]=t,"transitionProperty"!==n&&(e.style.transitionProperty=t))}function a(e,t){var n=r();n&&(e.style[n]=t,"transform"!==n&&(e.style.transform=t))}function s(e){return e.style.transitionProperty||e.style[i()]}function l(e){var t=window.getComputedStyle(e,null),n=t.getPropertyValue("transform")||t.getPropertyValue(r());if(n&&"none"!==n){var i=n.replace(/[^0-9\-.,]/g,"").split(",");return{x:parseFloat(i[12]||i[4],0),y:parseFloat(i[13]||i[5],0)}}return{x:0,y:0}}function u(e,t){var n=window.getComputedStyle(e,null),i=n.getPropertyValue("transform")||n.getPropertyValue(r());if(i&&"none"!==i){var o=void 0,s=i.match(f);if(s)s=s[1],o=s.split(",").map(function(e){return parseFloat(e,10)}),o[4]=t.x,o[5]=t.y,a(e,"matrix("+o.join(",")+")");else{var l=i.match(p)[1];o=l.split(",").map(function(e){return parseFloat(e,10)}),o[12]=t.x,o[13]=t.y,a(e,"matrix3d("+o.join(",")+")")}}else a(e,"translateX("+t.x+"px) translateY("+t.y+"px) translateZ(0)")}Object.defineProperty(t,"__esModule",{value:!0}),t.getTransformName=r,t.setTransitionProperty=o,t.getTransitionProperty=s,t.getTransformXY=l,t.setTransformXY=u;var c=void 0,d={Webkit:"-webkit-",Moz:"-moz-",ms:"-ms-",O:"-o-"},f=/matrix\((.*)\)/,p=/matrix3d\((.*)\)/},function(e,t,n){var i;/*! Copyright (c) 2015 Jed Watson. Based on code that is Copyright 2013-2015, Facebook, Inc. All rights reserved. */ !function(){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen};i=function(){return o}.call(t,n,t,e),!(void 0!==i&&(e.exports=i))}()},function(e,t){},280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,function(e,t){"use strict";function n(e){return function(){return e}}var i=function(){};i.thatReturns=n,i.thatReturnsFalse=n(!1),i.thatReturnsTrue=n(!0),i.thatReturnsNull=n(null),i.thatReturnsThis=function(){return this},i.thatReturnsArgument=function(e){return e},e.exports=i},function(e,t,n){"use strict";function i(e){if(Array.isArray(e))return 0===e.length;if("object"==typeof e){if(e){r(e)&&void 0!==e.size?o(!1):void 0;for(var t in e)return!1}return!0}return!e}function r(e){return"undefined"!=typeof Symbol&&e[Symbol.iterator]}var o=n(104);e.exports=i},function(e,t){/*! * for-in <https://github.com/jonschlinkert/for-in> * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ "use strict";e.exports=function(e,t,n){for(var i in e)if(t.call(n,e[i],i,e)===!1)break}},function(e,t,n){/*! * for-own <https://github.com/jonschlinkert/for-own> * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ "use strict";var i=n(327),r=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){i(e,function(i,o){if(r.call(e,o))return t.call(n,e[o],o,e)})}},function(e,t,n){var i;/*! Hammer.JS - v2.0.7 - 2016-04-22 * http://hammerjs.github.io/ * * Copyright (c) 2016 Jorik Tangelder; * Licensed under the MIT license */ !function(r,o,a,s){"use strict";function l(e,t,n){return setTimeout(p(e,n),t)}function u(e,t,n){return!!Array.isArray(e)&&(c(e,n[t],n),!0)}function c(e,t,n){var i;if(e)if(e.forEach)e.forEach(t,n);else if(e.length!==s)for(i=0;i<e.length;)t.call(n,e[i],i,e),i++;else for(i in e)e.hasOwnProperty(i)&&t.call(n,e[i],i,e)}function d(e,t,n){var i="DEPRECATED METHOD: "+t+"\n"+n+" AT \n";return function(){var t=new Error("get-stack-trace"),n=t&&t.stack?t.stack.replace(/^[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^Object.<anonymous>\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",o=r.console&&(r.console.warn||r.console.log);return o&&o.call(r.console,i,n),e.apply(this,arguments)}}function f(e,t,n){var i,r=t.prototype;i=e.prototype=Object.create(r),i.constructor=e,i._super=r,n&&me(i,n)}function p(e,t){return function(){return e.apply(t,arguments)}}function h(e,t){return typeof e==ge?e.apply(t?t[0]||s:s,t):e}function m(e,t){return e===s?t:e}function y(e,t,n){c(M(t),function(t){e.addEventListener(t,n,!1)})}function v(e,t,n){c(M(t),function(t){e.removeEventListener(t,n,!1)})}function g(e,t){for(;e;){if(e==t)return!0;e=e.parentNode}return!1}function b(e,t){return e.indexOf(t)>-1}function M(e){return e.trim().split(/\s+/g)}function T(e,t,n){if(e.indexOf&&!n)return e.indexOf(t);for(var i=0;i<e.length;){if(n&&e[i][n]==t||!n&&e[i]===t)return i;i++}return-1}function x(e){return Array.prototype.slice.call(e,0)}function C(e,t,n){for(var i=[],r=[],o=0;o<e.length;){var a=t?e[o][t]:e[o];T(r,a)<0&&i.push(e[o]),r[o]=a,o++}return n&&(i=t?i.sort(function(e,n){return e[t]>n[t]}):i.sort()),i}function _(e,t){for(var n,i,r=t[0].toUpperCase()+t.slice(1),o=0;o<ye.length;){if(n=ye[o],i=n?n+r:t,i in e)return i;o++}return s}function w(){return _e++}function S(e){var t=e.ownerDocument||e;return t.defaultView||t.parentWindow||r}function N(e,t){var n=this;this.manager=e,this.callback=t,this.element=e.element,this.target=e.options.inputTarget,this.domHandler=function(t){h(e.options.enable,[e])&&n.handler(t)},this.init()}function E(e){var t,n=e.options.inputClass;return new(t=n?n:Ne?B:Ee?V:Se?G:H)(e,P)}function P(e,t,n){var i=n.pointers.length,r=n.changedPointers.length,o=t&ke&&i-r===0,a=t&(Ae|ze)&&i-r===0;n.isFirst=!!o,n.isFinal=!!a,o&&(e.session={}),n.eventType=t,D(e,n),e.emit("hammer.input",n),e.recognize(n),e.session.prevInput=n}function D(e,t){var n=e.session,i=t.pointers,r=i.length;n.firstInput||(n.firstInput=j(t)),r>1&&!n.firstMultiple?n.firstMultiple=j(t):1===r&&(n.firstMultiple=!1);var o=n.firstInput,a=n.firstMultiple,s=a?a.center:o.center,l=t.center=k(i);t.timeStamp=Te(),t.deltaTime=t.timeStamp-o.timeStamp,t.angle=R(s,l),t.distance=z(s,l),I(n,t),t.offsetDirection=A(t.deltaX,t.deltaY);var u=O(t.deltaTime,t.deltaX,t.deltaY);t.overallVelocityX=u.x,t.overallVelocityY=u.y,t.overallVelocity=Me(u.x)>Me(u.y)?u.x:u.y,t.scale=a?Y(a.pointers,i):1,t.rotation=a?W(a.pointers,i):0,t.maxPointers=n.prevInput?t.pointers.length>n.prevInput.maxPointers?t.pointers.length:n.prevInput.maxPointers:t.pointers.length,L(n,t);var c=e.element;g(t.srcEvent.target,c)&&(c=t.srcEvent.target),t.target=c}function I(e,t){var n=t.center,i=e.offsetDelta||{},r=e.prevDelta||{},o=e.prevInput||{};t.eventType!==ke&&o.eventType!==Ae||(r=e.prevDelta={x:o.deltaX||0,y:o.deltaY||0},i=e.offsetDelta={x:n.x,y:n.y}),t.deltaX=r.x+(n.x-i.x),t.deltaY=r.y+(n.y-i.y)}function L(e,t){var n,i,r,o,a=e.lastInterval||t,l=t.timeStamp-a.timeStamp;if(t.eventType!=ze&&(l>je||a.velocity===s)){var u=t.deltaX-a.deltaX,c=t.deltaY-a.deltaY,d=O(l,u,c);i=d.x,r=d.y,n=Me(d.x)>Me(d.y)?d.x:d.y,o=A(u,c),e.lastInterval=t}else n=a.velocity,i=a.velocityX,r=a.velocityY,o=a.direction;t.velocity=n,t.velocityX=i,t.velocityY=r,t.direction=o}function j(e){for(var t=[],n=0;n<e.pointers.length;)t[n]={clientX:be(e.pointers[n].clientX),clientY:be(e.pointers[n].clientY)},n++;return{timeStamp:Te(),pointers:t,center:k(t),deltaX:e.deltaX,deltaY:e.deltaY}}function k(e){var t=e.length;if(1===t)return{x:be(e[0].clientX),y:be(e[0].clientY)};for(var n=0,i=0,r=0;r<t;)n+=e[r].clientX,i+=e[r].clientY,r++;return{x:be(n/t),y:be(i/t)}}function O(e,t,n){return{x:t/e||0,y:n/e||0}}function A(e,t){return e===t?Re:Me(e)>=Me(t)?e<0?We:Ye:t<0?He:Be}function z(e,t,n){n||(n=Qe);var i=t[n[0]]-e[n[0]],r=t[n[1]]-e[n[1]];return Math.sqrt(i*i+r*r)}function R(e,t,n){n||(n=Qe);var i=t[n[0]]-e[n[0]],r=t[n[1]]-e[n[1]];return 180*Math.atan2(r,i)/Math.PI}function W(e,t){return R(t[1],t[0],Ge)+R(e[1],e[0],Ge)}function Y(e,t){return z(t[0],t[1],Ge)/z(e[0],e[1],Ge)}function H(){this.evEl=Xe,this.evWin=Je,this.pressed=!1,N.apply(this,arguments)}function B(){this.evEl=$e,this.evWin=et,N.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function U(){this.evTarget=nt,this.evWin=it,this.started=!1,N.apply(this,arguments)}function F(e,t){var n=x(e.touches),i=x(e.changedTouches);return t&(Ae|ze)&&(n=C(n.concat(i),"identifier",!0)),[n,i]}function V(){this.evTarget=ot,this.targetIds={},N.apply(this,arguments)}function Q(e,t){var n=x(e.touches),i=this.targetIds;if(t&(ke|Oe)&&1===n.length)return i[n[0].identifier]=!0,[n,n];var r,o,a=x(e.changedTouches),s=[],l=this.target;if(o=n.filter(function(e){return g(e.target,l)}),t===ke)for(r=0;r<o.length;)i[o[r].identifier]=!0,r++;for(r=0;r<a.length;)i[a[r].identifier]&&s.push(a[r]),t&(Ae|ze)&&delete i[a[r].identifier],r++;return s.length?[C(o.concat(s),"identifier",!0),s]:void 0}function G(){N.apply(this,arguments);var e=p(this.handler,this);this.touch=new V(this.manager,e),this.mouse=new H(this.manager,e),this.primaryTouch=null,this.lastTouches=[]}function Z(e,t){e&ke?(this.primaryTouch=t.changedPointers[0].identifier,X.call(this,t)):e&(Ae|ze)&&X.call(this,t)}function X(e){var t=e.changedPointers[0];if(t.identifier===this.primaryTouch){var n={x:t.clientX,y:t.clientY};this.lastTouches.push(n);var i=this.lastTouches,r=function(){var e=i.indexOf(n);e>-1&&i.splice(e,1)};setTimeout(r,at)}}function J(e){for(var t=e.srcEvent.clientX,n=e.srcEvent.clientY,i=0;i<this.lastTouches.length;i++){var r=this.lastTouches[i],o=Math.abs(t-r.x),a=Math.abs(n-r.y);if(o<=st&&a<=st)return!0}return!1}function K(e,t){this.manager=e,this.set(t)}function q(e){if(b(e,pt))return pt;var t=b(e,ht),n=b(e,mt);return t&&n?pt:t||n?t?ht:mt:b(e,ft)?ft:dt}function $(){if(!ut)return!1;var e={},t=r.CSS&&r.CSS.supports;return["auto","manipulation","pan-y","pan-x","pan-x pan-y","none"].forEach(function(n){e[n]=!t||r.CSS.supports("touch-action",n)}),e}function ee(e){this.options=me({},this.defaults,e||{}),this.id=w(),this.manager=null,this.options.enable=m(this.options.enable,!0),this.state=vt,this.simultaneous={},this.requireFail=[]}function te(e){return e&xt?"cancel":e&Mt?"end":e&bt?"move":e&gt?"start":""}function ne(e){return e==Be?"down":e==He?"up":e==We?"left":e==Ye?"right":""}function ie(e,t){var n=t.manager;return n?n.get(e):e}function re(){ee.apply(this,arguments)}function oe(){re.apply(this,arguments),this.pX=null,this.pY=null}function ae(){re.apply(this,arguments)}function se(){ee.apply(this,arguments),this._timer=null,this._input=null}function le(){re.apply(this,arguments)}function ue(){re.apply(this,arguments)}function ce(){ee.apply(this,arguments),this.pTime=!1,this.pCenter=!1,this._timer=null,this._input=null,this.count=0}function de(e,t){return t=t||{},t.recognizers=m(t.recognizers,de.defaults.preset),new fe(e,t)}function fe(e,t){this.options=me({},de.defaults,t||{}),this.options.inputTarget=this.options.inputTarget||e,this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=e,this.input=E(this),this.touchAction=new K(this,this.options.touchAction),pe(this,!0),c(this.options.recognizers,function(e){var t=this.add(new e[0](e[1]));e[2]&&t.recognizeWith(e[2]),e[3]&&t.requireFailure(e[3])},this)}function pe(e,t){var n=e.element;if(n.style){var i;c(e.options.cssProps,function(r,o){i=_(n.style,o),t?(e.oldCssProps[i]=n.style[i],n.style[i]=r):n.style[i]=e.oldCssProps[i]||""}),t||(e.oldCssProps={})}}function he(e,t){var n=o.createEvent("Event");n.initEvent(e,!0,!0),n.gesture=t,t.target.dispatchEvent(n)}var me,ye=["","webkit","Moz","MS","ms","o"],ve=o.createElement("div"),ge="function",be=Math.round,Me=Math.abs,Te=Date.now;me="function"!=typeof Object.assign?function(e){if(e===s||null===e)throw new TypeError("Cannot convert undefined or null to object");for(var t=Object(e),n=1;n<arguments.length;n++){var i=arguments[n];if(i!==s&&null!==i)for(var r in i)i.hasOwnProperty(r)&&(t[r]=i[r])}return t}:Object.assign;var xe=d(function(e,t,n){for(var i=Object.keys(t),r=0;r<i.length;)(!n||n&&e[i[r]]===s)&&(e[i[r]]=t[i[r]]),r++;return e},"extend","Use `assign`."),Ce=d(function(e,t){return xe(e,t,!0)},"merge","Use `assign`."),_e=1,we=/mobile|tablet|ip(ad|hone|od)|android/i,Se="ontouchstart"in r,Ne=_(r,"PointerEvent")!==s,Ee=Se&&we.test(navigator.userAgent),Pe="touch",De="pen",Ie="mouse",Le="kinect",je=25,ke=1,Oe=2,Ae=4,ze=8,Re=1,We=2,Ye=4,He=8,Be=16,Ue=We|Ye,Fe=He|Be,Ve=Ue|Fe,Qe=["x","y"],Ge=["clientX","clientY"];N.prototype={handler:function(){},init:function(){this.evEl&&y(this.element,this.evEl,this.domHandler),this.evTarget&&y(this.target,this.evTarget,this.domHandler),this.evWin&&y(S(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&v(this.element,this.evEl,this.domHandler),this.evTarget&&v(this.target,this.evTarget,this.domHandler),this.evWin&&v(S(this.element),this.evWin,this.domHandler)}};var Ze={mousedown:ke,mousemove:Oe,mouseup:Ae},Xe="mousedown",Je="mousemove mouseup";f(H,N,{handler:function(e){var t=Ze[e.type];t&ke&&0===e.button&&(this.pressed=!0),t&Oe&&1!==e.which&&(t=Ae),this.pressed&&(t&Ae&&(this.pressed=!1),this.callback(this.manager,t,{pointers:[e],changedPointers:[e],pointerType:Ie,srcEvent:e}))}});var Ke={pointerdown:ke,pointermove:Oe,pointerup:Ae,pointercancel:ze,pointerout:ze},qe={2:Pe,3:De,4:Ie,5:Le},$e="pointerdown",et="pointermove pointerup pointercancel";r.MSPointerEvent&&!r.PointerEvent&&($e="MSPointerDown",et="MSPointerMove MSPointerUp MSPointerCancel"),f(B,N,{handler:function(e){var t=this.store,n=!1,i=e.type.toLowerCase().replace("ms",""),r=Ke[i],o=qe[e.pointerType]||e.pointerType,a=o==Pe,s=T(t,e.pointerId,"pointerId");r&ke&&(0===e.button||a)?s<0&&(t.push(e),s=t.length-1):r&(Ae|ze)&&(n=!0),s<0||(t[s]=e,this.callback(this.manager,r,{pointers:t,changedPointers:[e],pointerType:o,srcEvent:e}),n&&t.splice(s,1))}});var tt={touchstart:ke,touchmove:Oe,touchend:Ae,touchcancel:ze},nt="touchstart",it="touchstart touchmove touchend touchcancel";f(U,N,{handler:function(e){var t=tt[e.type];if(t===ke&&(this.started=!0),this.started){var n=F.call(this,e,t);t&(Ae|ze)&&n[0].length-n[1].length===0&&(this.started=!1),this.callback(this.manager,t,{pointers:n[0],changedPointers:n[1],pointerType:Pe,srcEvent:e})}}});var rt={touchstart:ke,touchmove:Oe,touchend:Ae,touchcancel:ze},ot="touchstart touchmove touchend touchcancel";f(V,N,{handler:function(e){var t=rt[e.type],n=Q.call(this,e,t);n&&this.callback(this.manager,t,{pointers:n[0],changedPointers:n[1],pointerType:Pe,srcEvent:e})}});var at=2500,st=25;f(G,N,{handler:function(e,t,n){var i=n.pointerType==Pe,r=n.pointerType==Ie;if(!(r&&n.sourceCapabilities&&n.sourceCapabilities.firesTouchEvents)){if(i)Z.call(this,t,n);else if(r&&J.call(this,n))return;this.callback(e,t,n)}},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var lt=_(ve.style,"touchAction"),ut=lt!==s,ct="compute",dt="auto",ft="manipulation",pt="none",ht="pan-x",mt="pan-y",yt=$();K.prototype={set:function(e){e==ct&&(e=this.compute()),ut&&this.manager.element.style&&yt[e]&&(this.manager.element.style[lt]=e),this.actions=e.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var e=[];return c(this.manager.recognizers,function(t){h(t.options.enable,[t])&&(e=e.concat(t.getTouchAction()))}),q(e.join(" "))},preventDefaults:function(e){var t=e.srcEvent,n=e.offsetDirection;if(this.manager.session.prevented)return void t.preventDefault();var i=this.actions,r=b(i,pt)&&!yt[pt],o=b(i,mt)&&!yt[mt],a=b(i,ht)&&!yt[ht];if(r){var s=1===e.pointers.length,l=e.distance<2,u=e.deltaTime<250;if(s&&l&&u)return}return a&&o?void 0:r||o&&n&Ue||a&&n&Fe?this.preventSrc(t):void 0},preventSrc:function(e){this.manager.session.prevented=!0,e.preventDefault()}};var vt=1,gt=2,bt=4,Mt=8,Tt=Mt,xt=16,Ct=32;ee.prototype={defaults:{},set:function(e){return me(this.options,e),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(e){if(u(e,"recognizeWith",this))return this;var t=this.simultaneous;return e=ie(e,this),t[e.id]||(t[e.id]=e,e.recognizeWith(this)),this},dropRecognizeWith:function(e){return u(e,"dropRecognizeWith",this)?this:(e=ie(e,this),delete this.simultaneous[e.id],this)},requireFailure:function(e){if(u(e,"requireFailure",this))return this;var t=this.requireFail;return e=ie(e,this),T(t,e)===-1&&(t.push(e),e.requireFailure(this)),this},dropRequireFailure:function(e){if(u(e,"dropRequireFailure",this))return this;e=ie(e,this);var t=T(this.requireFail,e);return t>-1&&this.requireFail.splice(t,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(e){return!!this.simultaneous[e.id]},emit:function(e){function t(t){n.manager.emit(t,e)}var n=this,i=this.state;i<Mt&&t(n.options.event+te(i)),t(n.options.event),e.additionalEvent&&t(e.additionalEvent),i>=Mt&&t(n.options.event+te(i))},tryEmit:function(e){return this.canEmit()?this.emit(e):void(this.state=Ct)},canEmit:function(){for(var e=0;e<this.requireFail.length;){if(!(this.requireFail[e].state&(Ct|vt)))return!1;e++}return!0},recognize:function(e){var t=me({},e);return h(this.options.enable,[this,t])?(this.state&(Tt|xt|Ct)&&(this.state=vt),this.state=this.process(t),void(this.state&(gt|bt|Mt|xt)&&this.tryEmit(t))):(this.reset(),void(this.state=Ct))},process:function(e){},getTouchAction:function(){},reset:function(){}},f(re,ee,{defaults:{pointers:1},attrTest:function(e){var t=this.options.pointers;return 0===t||e.pointers.length===t},process:function(e){var t=this.state,n=e.eventType,i=t&(gt|bt),r=this.attrTest(e);return i&&(n&ze||!r)?t|xt:i||r?n&Ae?t|Mt:t&gt?t|bt:gt:Ct}}),f(oe,re,{defaults:{event:"pan",threshold:10,pointers:1,direction:Ve},getTouchAction:function(){var e=this.options.direction,t=[];return e&Ue&&t.push(mt),e&Fe&&t.push(ht),t},directionTest:function(e){var t=this.options,n=!0,i=e.distance,r=e.direction,o=e.deltaX,a=e.deltaY;return r&t.direction||(t.direction&Ue?(r=0===o?Re:o<0?We:Ye,n=o!=this.pX,i=Math.abs(e.deltaX)):(r=0===a?Re:a<0?He:Be,n=a!=this.pY,i=Math.abs(e.deltaY))),e.direction=r,n&&i>t.threshold&&r&t.direction},attrTest:function(e){return re.prototype.attrTest.call(this,e)&&(this.state&gt||!(this.state&gt)&&this.directionTest(e))},emit:function(e){this.pX=e.deltaX,this.pY=e.deltaY;var t=ne(e.direction);t&&(e.additionalEvent=this.options.event+t),this._super.emit.call(this,e)}}),f(ae,re,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[pt]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.scale-1)>this.options.threshold||this.state&gt)},emit:function(e){if(1!==e.scale){var t=e.scale<1?"in":"out";e.additionalEvent=this.options.event+t}this._super.emit.call(this,e)}}),f(se,ee,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[dt]},process:function(e){var t=this.options,n=e.pointers.length===t.pointers,i=e.distance<t.threshold,r=e.deltaTime>t.time;if(this._input=e,!i||!n||e.eventType&(Ae|ze)&&!r)this.reset();else if(e.eventType&ke)this.reset(),this._timer=l(function(){this.state=Tt,this.tryEmit()},t.time,this);else if(e.eventType&Ae)return Tt;return Ct},reset:function(){clearTimeout(this._timer)},emit:function(e){this.state===Tt&&(e&&e.eventType&Ae?this.manager.emit(this.options.event+"up",e):(this._input.timeStamp=Te(),this.manager.emit(this.options.event,this._input)))}}),f(le,re,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[pt]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.rotation)>this.options.threshold||this.state&gt)}}),f(ue,re,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:Ue|Fe,pointers:1},getTouchAction:function(){return oe.prototype.getTouchAction.call(this)},attrTest:function(e){var t,n=this.options.direction;return n&(Ue|Fe)?t=e.overallVelocity:n&Ue?t=e.overallVelocityX:n&Fe&&(t=e.overallVelocityY),this._super.attrTest.call(this,e)&&n&e.offsetDirection&&e.distance>this.options.threshold&&e.maxPointers==this.options.pointers&&Me(t)>this.options.velocity&&e.eventType&Ae},emit:function(e){var t=ne(e.offsetDirection);t&&this.manager.emit(this.options.event+t,e),this.manager.emit(this.options.event,e)}}),f(ce,ee,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[ft]},process:function(e){var t=this.options,n=e.pointers.length===t.pointers,i=e.distance<t.threshold,r=e.deltaTime<t.time;if(this.reset(),e.eventType&ke&&0===this.count)return this.failTimeout();if(i&&r&&n){if(e.eventType!=Ae)return this.failTimeout();var o=!this.pTime||e.timeStamp-this.pTime<t.interval,a=!this.pCenter||z(this.pCenter,e.center)<t.posThreshold;this.pTime=e.timeStamp,this.pCenter=e.center,a&&o?this.count+=1:this.count=1,this._input=e;var s=this.count%t.taps;if(0===s)return this.hasRequireFailures()?(this._timer=l(function(){this.state=Tt,this.tryEmit()},t.interval,this),gt):Tt}return Ct},failTimeout:function(){return this._timer=l(function(){this.state=Ct},this.options.interval,this),Ct},reset:function(){clearTimeout(this._timer)},emit:function(){this.state==Tt&&(this._input.tapCount=this.count,this.manager.emit(this.options.event,this._input))}}),de.VERSION="2.0.7",de.defaults={domEvents:!1,touchAction:ct,enable:!0,inputTarget:null,inputClass:null,preset:[[le,{enable:!1}],[ae,{enable:!1},["rotate"]],[ue,{direction:Ue}],[oe,{direction:Ue},["swipe"]],[ce],[ce,{event:"doubletap",taps:2},["tap"]],[se]],cssProps:{userSelect:"none",touchSelect:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}};var _t=1,wt=2;fe.prototype={set:function(e){return me(this.options,e),e.touchAction&&this.touchAction.update(),e.inputTarget&&(this.input.destroy(),this.input.target=e.inputTarget,this.input.init()),this},stop:function(e){this.session.stopped=e?wt:_t},recognize:function(e){var t=this.session;if(!t.stopped){this.touchAction.preventDefaults(e);var n,i=this.recognizers,r=t.curRecognizer;(!r||r&&r.state&Tt)&&(r=t.curRecognizer=null);for(var o=0;o<i.length;)n=i[o],t.stopped===wt||r&&n!=r&&!n.canRecognizeWith(r)?n.reset():n.recognize(e),!r&&n.state&(gt|bt|Mt)&&(r=t.curRecognizer=n),o++}},get:function(e){if(e instanceof ee)return e;for(var t=this.recognizers,n=0;n<t.length;n++)if(t[n].options.event==e)return t[n];return null},add:function(e){if(u(e,"add",this))return this;var t=this.get(e.options.event);return t&&this.remove(t),this.recognizers.push(e),e.manager=this,this.touchAction.update(),e},remove:function(e){if(u(e,"remove",this))return this;if(e=this.get(e)){var t=this.recognizers,n=T(t,e);n!==-1&&(t.splice(n,1),this.touchAction.update())}return this},on:function(e,t){if(e!==s&&t!==s){var n=this.handlers;return c(M(e),function(e){n[e]=n[e]||[],n[e].push(t)}),this}},off:function(e,t){if(e!==s){var n=this.handlers;return c(M(e),function(e){t?n[e]&&n[e].splice(T(n[e],t),1):delete n[e]}),this}},emit:function(e,t){this.options.domEvents&&he(e,t);var n=this.handlers[e]&&this.handlers[e].slice();if(n&&n.length){t.type=e,t.preventDefault=function(){t.srcEvent.preventDefault()};for(var i=0;i<n.length;)n[i](t),i++}},destroy:function(){this.element&&pe(this,!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}},me(de,{INPUT_START:ke,INPUT_MOVE:Oe,INPUT_END:Ae,INPUT_CANCEL:ze,STATE_POSSIBLE:vt,STATE_BEGAN:gt,STATE_CHANGED:bt,STATE_ENDED:Mt,STATE_RECOGNIZED:Tt,STATE_CANCELLED:xt,STATE_FAILED:Ct,DIRECTION_NONE:Re,DIRECTION_LEFT:We,DIRECTION_RIGHT:Ye,DIRECTION_UP:He,DIRECTION_DOWN:Be,DIRECTION_HORIZONTAL:Ue,DIRECTION_VERTICAL:Fe,DIRECTION_ALL:Ve,Manager:fe,Input:N,TouchAction:K,TouchInput:V,MouseInput:H,PointerEventInput:B,TouchMouseInput:G,SingleTouchInput:U,Recognizer:ee,AttrRecognizer:re,Tap:ce,Pan:oe,Swipe:ue,Pinch:ae,Rotate:le,Press:se,on:y,off:v,each:c,merge:Ce,extend:xe,assign:me,inherit:f,bindFn:p,prefixed:_});var St="undefined"!=typeof r?r:"undefined"!=typeof self?self:{};St.Hammer=de,i=function(){return de}.call(t,n,t,e),!(i!==s&&(e.exports=i))}(window,document,"Hammer")},function(e,t){/*! * is-extendable <https://github.com/jonschlinkert/is-extendable> * * Copyright (c) 2015, Jon Schlinkert. * Licensed under the MIT License. */ "use strict";e.exports=function(e){return"undefined"!=typeof e&&null!==e&&("object"==typeof e||"function"==typeof e)}},function(e,t,n){!function(t,n){e.exports=n()}(this,function(){return function(e){function t(i){if(n[i])return n[i].exports;var r=n[i]={exports:{},id:i,loaded:!1};return e[i].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}({0:/*!*****************!*\ !*** multi lib ***! \*****************/ function(e,t,n){e.exports=n(/*! ./index.js */169)},5:/*!******************************!*\ !*** ./~/process/browser.js ***! \******************************/ function(e,t){function n(){u=!1,a.length?l=a.concat(l):c=-1,l.length&&i()}function i(){if(!u){var e=setTimeout(n);u=!0;for(var t=l.length;t;){for(a=l,l=[];++c<t;)a&&a[c].run();c=-1,t=l.length}a=null,u=!1,clearTimeout(e)}}function r(e,t){this.fun=e,this.array=t}function o(){}var a,s=e.exports={},l=[],u=!1,c=-1;s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];l.push(new r(e,t)),1!==l.length||u||setTimeout(i,0)},r.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=o,s.addListener=o,s.once=o,s.off=o,s.removeListener=o,s.removeAllListeners=o,s.emit=o,s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},169:/*!******************!*\ !*** ./index.js ***! \******************/ function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(/*! tween-functions */170),o=i(r),a=n(/*! raf */171),s=i(a),l="ADDITIVE",u=r.easeInOutQuad,c=300,d=0,f={ADDITIVE:"ADDITIVE",DESTRUCTIVE:"DESTRUCTIVE"},p={_rafID:null,getInitialState:function(){return{tweenQueue:[]}},componentWillUnmount:function(){s["default"].cancel(this._rafID),this._rafID=-1},tweenState:function(e,t){var n=this,i=t.easing,r=t.duration,o=t.delay,a=t.beginValue,p=t.endValue,h=t.onEnd,m=t.stackBehavior;this.setState(function(t){var y=t,v=void 0,g=void 0;if("string"==typeof e)v=e,g=e;else{for(var b=0;b<e.length-1;b++)y=y[e[b]];v=e[e.length-1],g=e.join("|")}var M={easing:i||u,duration:null==r?c:r,delay:null==o?d:o,beginValue:null==a?y[v]:a,endValue:p,onEnd:h,stackBehavior:m||l},T=t.tweenQueue;return M.stackBehavior===f.DESTRUCTIVE&&(T=t.tweenQueue.filter(function(e){return e.pathHash!==g})),T.push({pathHash:g,config:M,initTime:Date.now()+M.delay}),y[v]=M.endValue,1===T.length&&(n._rafID=(0,s["default"])(n._rafCb)),{tweenQueue:T}})},getTweeningValue:function(e){var t=this.state,n=void 0,i=void 0;if("string"==typeof e)n=t[e],i=e;else{n=t;for(var r=0;r<e.length;r++)n=n[e[r]];i=e.join("|")}for(var o=Date.now(),r=0;r<t.tweenQueue.length;r++){var a=t.tweenQueue[r],s=a.pathHash,l=a.initTime,u=a.config;if(s===i){var c=o-l>u.duration?u.duration:Math.max(0,o-l),d=0===u.duration?u.endValue:u.easing(c,u.beginValue,u.endValue,u.duration),f=d-u.endValue;n+=f}}return n},_rafCb:function(){var e=this.state;if(0!==e.tweenQueue.length){for(var t=Date.now(),n=[],i=0;i<e.tweenQueue.length;i++){var r=e.tweenQueue[i],o=r.initTime,a=r.config;t-o<a.duration?n.push(r):a.onEnd&&a.onEnd()}this._rafID!==-1&&(this.setState({tweenQueue:n}),this._rafID=(0,s["default"])(this._rafCb))}}};t["default"]={Mixin:p,easingTypes:o["default"],stackBehavior:f},e.exports=t["default"]},170:/*!************************************!*\ !*** ./~/tween-functions/index.js ***! \************************************/ function(e,t){"use strict";var n={linear:function(e,t,n,i){var r=n-t;return r*e/i+t},easeInQuad:function(e,t,n,i){var r=n-t;return r*(e/=i)*e+t},easeOutQuad:function(e,t,n,i){var r=n-t;return-r*(e/=i)*(e-2)+t},easeInOutQuad:function(e,t,n,i){var r=n-t;return(e/=i/2)<1?r/2*e*e+t:-r/2*(--e*(e-2)-1)+t},easeInCubic:function(e,t,n,i){var r=n-t;return r*(e/=i)*e*e+t},easeOutCubic:function(e,t,n,i){var r=n-t;return r*((e=e/i-1)*e*e+1)+t},easeInOutCubic:function(e,t,n,i){var r=n-t;return(e/=i/2)<1?r/2*e*e*e+t:r/2*((e-=2)*e*e+2)+t},easeInQuart:function(e,t,n,i){var r=n-t;return r*(e/=i)*e*e*e+t},easeOutQuart:function(e,t,n,i){var r=n-t;return-r*((e=e/i-1)*e*e*e-1)+t},easeInOutQuart:function(e,t,n,i){var r=n-t;return(e/=i/2)<1?r/2*e*e*e*e+t:-r/2*((e-=2)*e*e*e-2)+t},easeInQuint:function(e,t,n,i){var r=n-t;return r*(e/=i)*e*e*e*e+t},easeOutQuint:function(e,t,n,i){var r=n-t;return r*((e=e/i-1)*e*e*e*e+1)+t},easeInOutQuint:function(e,t,n,i){var r=n-t;return(e/=i/2)<1?r/2*e*e*e*e*e+t:r/2*((e-=2)*e*e*e*e+2)+t},easeInSine:function(e,t,n,i){var r=n-t;return-r*Math.cos(e/i*(Math.PI/2))+r+t},easeOutSine:function(e,t,n,i){var r=n-t;return r*Math.sin(e/i*(Math.PI/2))+t},easeInOutSine:function(e,t,n,i){var r=n-t;return-r/2*(Math.cos(Math.PI*e/i)-1)+t},easeInExpo:function(e,t,n,i){var r=n-t;return 0==e?t:r*Math.pow(2,10*(e/i-1))+t},easeOutExpo:function(e,t,n,i){var r=n-t;return e==i?t+r:r*(-Math.pow(2,-10*e/i)+1)+t},easeInOutExpo:function(e,t,n,i){var r=n-t;return 0===e?t:e===i?t+r:(e/=i/2)<1?r/2*Math.pow(2,10*(e-1))+t:r/2*(-Math.pow(2,-10*--e)+2)+t},easeInCirc:function(e,t,n,i){var r=n-t;return-r*(Math.sqrt(1-(e/=i)*e)-1)+t},easeOutCirc:function(e,t,n,i){var r=n-t;return r*Math.sqrt(1-(e=e/i-1)*e)+t},easeInOutCirc:function(e,t,n,i){var r=n-t;return(e/=i/2)<1?-r/2*(Math.sqrt(1-e*e)-1)+t:r/2*(Math.sqrt(1-(e-=2)*e)+1)+t},easeInElastic:function(e,t,n,i){var r,o,a,s=n-t;return a=1.70158,o=0,r=s,0===e?t:1===(e/=i)?t+s:(o||(o=.3*i),r<Math.abs(s)?(r=s,a=o/4):a=o/(2*Math.PI)*Math.asin(s/r),-(r*Math.pow(2,10*(e-=1))*Math.sin((e*i-a)*(2*Math.PI)/o))+t)},easeOutElastic:function(e,t,n,i){var r,o,a,s=n-t;return a=1.70158,o=0,r=s,0===e?t:1===(e/=i)?t+s:(o||(o=.3*i),r<Math.abs(s)?(r=s,a=o/4):a=o/(2*Math.PI)*Math.asin(s/r),r*Math.pow(2,-10*e)*Math.sin((e*i-a)*(2*Math.PI)/o)+s+t)},easeInOutElastic:function(e,t,n,i){var r,o,a,s=n-t;return a=1.70158,o=0,r=s,0===e?t:2===(e/=i/2)?t+s:(o||(o=i*(.3*1.5)),r<Math.abs(s)?(r=s,a=o/4):a=o/(2*Math.PI)*Math.asin(s/r),e<1?-.5*(r*Math.pow(2,10*(e-=1))*Math.sin((e*i-a)*(2*Math.PI)/o))+t:r*Math.pow(2,-10*(e-=1))*Math.sin((e*i-a)*(2*Math.PI)/o)*.5+s+t)},easeInBack:function(e,t,n,i,r){var o=n-t;return void 0===r&&(r=1.70158),o*(e/=i)*e*((r+1)*e-r)+t},easeOutBack:function(e,t,n,i,r){var o=n-t;return void 0===r&&(r=1.70158),o*((e=e/i-1)*e*((r+1)*e+r)+1)+t},easeInOutBack:function(e,t,n,i,r){var o=n-t;return void 0===r&&(r=1.70158),(e/=i/2)<1?o/2*(e*e*(((r*=1.525)+1)*e-r))+t:o/2*((e-=2)*e*(((r*=1.525)+1)*e+r)+2)+t},easeInBounce:function(e,t,i,r){var o,a=i-t;return o=n.easeOutBounce(r-e,0,a,r),a-o+t},easeOutBounce:function(e,t,n,i){var r=n-t;return(e/=i)<1/2.75?r*(7.5625*e*e)+t:e<2/2.75?r*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?r*(7.5625*(e-=2.25/2.75)*e+.9375)+t:r*(7.5625*(e-=2.625/2.75)*e+.984375)+t},easeInOutBounce:function(e,t,i,r){var o,a=i-t;return e<r/2?(o=n.easeInBounce(2*e,0,a,r),.5*o+t):(o=n.easeOutBounce(2*e-r,0,a,r),.5*o+.5*a+t)}};e.exports=n},171:/*!************************!*\ !*** ./~/raf/index.js ***! \************************/ function(e,t,n){(function(t){for(var i=n(/*! performance-now */172),r="undefined"==typeof window?t:window,o=["moz","webkit"],a="AnimationFrame",s=r["request"+a],l=r["cancel"+a]||r["cancelRequest"+a],u=0;!s&&u<o.length;u++)s=r[o[u]+"Request"+a],l=r[o[u]+"Cancel"+a]||r[o[u]+"CancelRequest"+a];if(!s||!l){var c=0,d=0,f=[],p=1e3/60;s=function(e){if(0===f.length){var t=i(),n=Math.max(0,p-(t-c));c=n+t,setTimeout(function(){var e=f.slice(0);f.length=0;for(var t=0;t<e.length;t++)if(!e[t].cancelled)try{e[t].callback(c)}catch(n){setTimeout(function(){throw n},0)}},Math.round(n))}return f.push({handle:++d,callback:e,cancelled:!1}),d},l=function(e){for(var t=0;t<f.length;t++)f[t].handle===e&&(f[t].cancelled=!0)}}e.exports=function(e){return s.call(r,e)},e.exports.cancel=function(){l.apply(r,arguments)},e.exports.polyfill=function(){r.requestAnimationFrame=s,r.cancelAnimationFrame=l}}).call(t,function(){return this}())},172:/*!**************************************************!*\ !*** ./~/performance-now/lib/performance-now.js ***! \**************************************************/ function(e,t,n){(function(t){(function(){var n,i,r;"undefined"!=typeof performance&&null!==performance&&performance.now?e.exports=function(){return performance.now()}:"undefined"!=typeof t&&null!==t&&t.hrtime?(e.exports=function(){return(n()-r)/1e6},i=t.hrtime,n=function(){var e;return e=i(),1e9*e[0]+e[1]},r=n()):Date.now?(e.exports=function(){return Date.now()-r},r=Date.now()):(e.exports=function(){return(new Date).getTime()-r},r=(new Date).getTime())}).call(this)}).call(t,n(/*! ./~/process/browser.js */5))}})})},function(e,t){function n(e){return!!e&&"object"==typeof e}function i(e,t){var n=null==e?void 0:e[t];return a(n)?n:void 0}function r(e){return o(e)&&f.call(e)==s}function o(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function a(e){return null!=e&&(r(e)?p.test(c.call(e)):n(e)&&l.test(e))}var s="[object Function]",l=/^\[object .+?Constructor\]$/,u=Object.prototype,c=Function.prototype.toString,d=u.hasOwnProperty,f=u.toString,p=RegExp("^"+c.call(d).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=i},function(e,t){function n(e){return r(e)&&h.call(e,"callee")&&(!y.call(e,"callee")||m.call(e)==c)}function i(e){return null!=e&&a(e.length)&&!o(e)}function r(e){return l(e)&&i(e)}function o(e){var t=s(e)?m.call(e):"";return t==d||t==f}function a(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=u}function s(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function l(e){return!!e&&"object"==typeof e}var u=9007199254740991,c="[object Arguments]",d="[object Function]",f="[object GeneratorFunction]",p=Object.prototype,h=p.hasOwnProperty,m=p.toString,y=p.propertyIsEnumerable;e.exports=n},function(e,t){function n(e){return!!e&&"object"==typeof e}function i(e,t){var n=null==e?void 0:e[t];return s(n)?n:void 0}function r(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=v}function o(e){return a(e)&&h.call(e)==u}function a(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function s(e){return null!=e&&(o(e)?m.test(f.call(e)):n(e)&&c.test(e))}var l="[object Array]",u="[object Function]",c=/^\[object .+?Constructor\]$/,d=Object.prototype,f=Function.prototype.toString,p=d.hasOwnProperty,h=d.toString,m=RegExp("^"+f.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),y=i(Array,"isArray"),v=9007199254740991,g=y||function(e){return n(e)&&r(e.length)&&h.call(e)==l};e.exports=g},function(e,t,n){function i(e){return function(t){return null==t?void 0:t[e]}}function r(e){return null!=e&&a(g(e))}function o(e,t){return e="number"==typeof e||p.test(e)?+e:-1,t=null==t?v:t,e>-1&&e%1==0&&e<t}function a(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=v}function s(e){for(var t=u(e),n=t.length,i=n&&e.length,r=!!i&&a(i)&&(f(e)||d(e)),s=-1,l=[];++s<n;){var c=t[s];(r&&o(c,i)||m.call(e,c))&&l.push(c)}return l}function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function u(e){if(null==e)return[];l(e)||(e=Object(e));var t=e.length;t=t&&a(t)&&(f(e)||d(e))&&t||0;for(var n=e.constructor,i=-1,r="function"==typeof n&&n.prototype===e,s=Array(t),u=t>0;++i<t;)s[i]=i+"";for(var c in e)u&&o(c,t)||"constructor"==c&&(r||!m.call(e,c))||s.push(c);return s}var c=n(332),d=n(333),f=n(334),p=/^\d+$/,h=Object.prototype,m=h.hasOwnProperty,y=c(Object,"keys"),v=9007199254740991,g=i("length"),b=y?function(e){var t=null==e?void 0:e.constructor;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&r(e)?s(e):l(e)?y(e):[]}:s;e.exports=b},function(e,t,n){"use strict";var i=n(337);e.exports=i},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},o=n(1),a=i(o),s=n(9),l=(i(s),n(331)),u=i(l),c=n(338),d=i(c),f=n(10),p=i(f),h=n(279),m=i(h),y=function(e,t,n){null!==e&&"undefined"!=typeof e&&(e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent?e.attachEvent("on"+t,n):e["on"+t]=n)},v=function(e,t,n){null!==e&&"undefined"!=typeof e&&(e.removeEventListener?e.removeEventListener(t,n,!1):e.detachEvent?e.detachEvent("on"+t,n):e["on"+t]=null)},g=a["default"].createClass({displayName:"Carousel",mixins:[u["default"].Mixin],propTypes:{afterSlide:a["default"].PropTypes.func,autoplay:a["default"].PropTypes.bool,autoplayInterval:a["default"].PropTypes.number,beforeSlide:a["default"].PropTypes.func,cellAlign:a["default"].PropTypes.oneOf(["left","center","right"]),cellSpacing:a["default"].PropTypes.number,data:a["default"].PropTypes.func,decorators:a["default"].PropTypes.arrayOf(a["default"].PropTypes.shape({component:a["default"].PropTypes.func,position:a["default"].PropTypes.oneOf(["TopLeft","TopCenter","TopRight","CenterLeft","CenterCenter","CenterRight","BottomLeft","BottomCenter","BottomRight"]),style:a["default"].PropTypes.object})),dragging:a["default"].PropTypes.bool,easing:a["default"].PropTypes.string,edgeEasing:a["default"].PropTypes.string,framePadding:a["default"].PropTypes.string,frameOverflow:a["default"].PropTypes.string,initialSlideHeight:a["default"].PropTypes.number,initialSlideWidth:a["default"].PropTypes.number,slideIndex:a["default"].PropTypes.number,slidesToShow:a["default"].PropTypes.number,slidesToScroll:a["default"].PropTypes.oneOfType([a["default"].PropTypes.number,a["default"].PropTypes.oneOf(["auto"])]),slideWidth:a["default"].PropTypes.oneOfType([a["default"].PropTypes.string,a["default"].PropTypes.number]),speed:a["default"].PropTypes.number,vertical:a["default"].PropTypes.bool,width:a["default"].PropTypes.string,wrapAround:a["default"].PropTypes.bool},getDefaultProps:function(){return{afterSlide:function(){},autoplay:!1,autoplayInterval:3e3,beforeSlide:function(){},cellAlign:"left",cellSpacing:0,data:function(){},decorators:d["default"],dragging:!0,easing:"easeOutCirc",edgeEasing:"easeOutElastic",framePadding:"0px",frameOverflow:"hidden",slideIndex:0,slidesToScroll:1,slidesToShow:1,slideWidth:1,speed:500,vertical:!1,width:"100%",wrapAround:!1}},getInitialState:function(){return{currentSlide:this.props.slideIndex,dragging:!1,frameWidth:0,left:0,slideCount:0,slidesToScroll:this.props.slidesToScroll,slideWidth:0,top:0}},componentWillMount:function(){this.setInitialDimensions()},componentDidMount:function(){this.setDimensions(),this.bindEvents(),this.setExternalData(),this.props.autoplay&&this.startAutoplay()},componentWillReceiveProps:function(e){this.setState({slideCount:e.children.length}),this.setDimensions(e),this.props.slideIndex!==e.slideIndex&&e.slideIndex!==this.state.currentSlide&&this.goToSlide(e.slideIndex),this.props.autoplay!==e.autoplay&&(e.autoplay?this.startAutoplay():this.stopAutoplay())},componentWillUnmount:function(){this.unbindEvents(),this.stopAutoplay()},render:function(){var e=this,t=a["default"].Children.count(this.props.children)>1?this.formatChildren(this.props.children):this.props.children;return a["default"].createElement("div",{className:["slider",this.props.className||""].join(" "),ref:"slider",style:(0,p["default"])(this.getSliderStyles(),this.props.style||{})},a["default"].createElement("div",r({className:"slider-frame",ref:"frame",style:this.getFrameStyles()},this.getTouchEvents(),this.getMouseEvents(),{onClick:this.handleClick}),a["default"].createElement("ul",{className:"slider-list",ref:"list",style:this.getListStyles()},t)),this.props.decorators?this.props.decorators.map(function(t,n){return a["default"].createElement("div",{style:(0,p["default"])(e.getDecoratorStyles(t.position),t.style||{}),className:"slider-decorator-"+n,key:n},a["default"].createElement(t.component,{currentSlide:e.state.currentSlide,slideCount:e.state.slideCount,frameWidth:e.state.frameWidth,slideWidth:e.state.slideWidth,slidesToScroll:e.state.slidesToScroll,cellSpacing:e.props.cellSpacing,slidesToShow:e.props.slidesToShow,wrapAround:e.props.wrapAround,nextSlide:e.nextSlide,previousSlide:e.previousSlide,goToSlide:e.goToSlide}))}):null,a["default"].createElement("style",{type:"text/css",dangerouslySetInnerHTML:{__html:e.getStyleTagStyles()}}))},touchObject:{},getTouchEvents:function(){var e=this;return{onTouchStart:function(t){e.touchObject={startX:t.touches[0].pageX,startY:t.touches[0].pageY},e.handleMouseOver()},onTouchMove:function(t){var n=e.swipeDirection(e.touchObject.startX,t.touches[0].pageX,e.touchObject.startY,t.touches[0].pageY);0!==n&&t.preventDefault();var i=e.props.vertical?Math.round(Math.sqrt(Math.pow(t.touches[0].pageY-e.touchObject.startY,2))):Math.round(Math.sqrt(Math.pow(t.touches[0].pageX-e.touchObject.startX,2)));e.touchObject={startX:e.touchObject.startX,startY:e.touchObject.startY,endX:t.touches[0].pageX,endY:t.touches[0].pageY,length:i,direction:n},e.setState({left:e.props.vertical?0:e.getTargetLeft(e.touchObject.length*e.touchObject.direction),top:e.props.vertical?e.getTargetLeft(e.touchObject.length*e.touchObject.direction):0})},onTouchEnd:function(t){e.handleSwipe(t),e.handleMouseOut()},onTouchCancel:function(t){e.handleSwipe(t)}}},clickSafe:!0,getMouseEvents:function(){var e=this;return this.props.dragging===!1?null:{onMouseOver:function(){e.handleMouseOver()},onMouseOut:function(){e.handleMouseOut()},onMouseDown:function(t){e.touchObject={startX:t.clientX,startY:t.clientY},e.setState({dragging:!0})},onMouseMove:function(t){if(e.state.dragging){var n=e.swipeDirection(e.touchObject.startX,t.clientX,e.touchObject.startY,t.clientY);0!==n&&t.preventDefault();var i=e.props.vertical?Math.round(Math.sqrt(Math.pow(t.clientY-e.touchObject.startY,2))):Math.round(Math.sqrt(Math.pow(t.clientX-e.touchObject.startX,2)));e.touchObject={startX:e.touchObject.startX,startY:e.touchObject.startY,endX:t.clientX,endY:t.clientY,length:i,direction:n},e.setState({left:e.props.vertical?0:e.getTargetLeft(e.touchObject.length*e.touchObject.direction),top:e.props.vertical?e.getTargetLeft(e.touchObject.length*e.touchObject.direction):0})}},onMouseUp:function(t){e.state.dragging&&e.handleSwipe(t)},onMouseLeave:function(t){e.state.dragging&&e.handleSwipe(t)}}},handleMouseOver:function(){this.props.autoplay&&(this.autoplayPaused=!0,this.stopAutoplay())},handleMouseOut:function(){this.props.autoplay&&this.autoplayPaused&&(this.startAutoplay(),this.autoplayPaused=null)},handleClick:function(e){this.clickSafe===!0&&(e.preventDefault(),e.stopPropagation(),e.nativeEvent&&e.nativeEvent.stopPropagation())},handleSwipe:function(e){"undefined"!=typeof this.touchObject.length&&this.touchObject.length>44?this.clickSafe=!0:this.clickSafe=!1;var t=this.props.slidesToShow;"auto"===this.props.slidesToScroll&&(t=this.state.slidesToScroll),this.touchObject.length>this.state.slideWidth/t/5?1===this.touchObject.direction?this.state.currentSlide>=a["default"].Children.count(this.props.children)-t&&!this.props.wrapAround?this.animateSlide(u["default"].easingTypes[this.props.edgeEasing]):this.nextSlide():this.touchObject.direction===-1&&(this.state.currentSlide<=0&&!this.props.wrapAround?this.animateSlide(u["default"].easingTypes[this.props.edgeEasing]):this.previousSlide()):this.goToSlide(this.state.currentSlide),this.touchObject={},this.setState({dragging:!1})},swipeDirection:function(e,t,n,i){var r,o,a,s;return r=e-t,o=n-i,a=Math.atan2(o,r),s=Math.round(180*a/Math.PI),s<0&&(s=360-Math.abs(s)),s<=45&&s>=0?1:s<=360&&s>=315?1:s>=135&&s<=225?-1:this.props.vertical===!0?s>=35&&s<=135?1:-1:0},autoplayIterator:function(){return this.props.wrapAround?this.nextSlide():void(this.state.currentSlide!==this.state.slideCount-this.state.slidesToShow?this.nextSlide():this.stopAutoplay())},startAutoplay:function(){this.autoplayID=setInterval(this.autoplayIterator,this.props.autoplayInterval)},resetAutoplay:function(){this.props.autoplay&&!this.autoplayPaused&&(this.stopAutoplay(),this.startAutoplay())},stopAutoplay:function(){this.autoplayID&&clearInterval(this.autoplayID)},goToSlide:function(e){var t=this;if(e>=a["default"].Children.count(this.props.children)||e<0){if(!this.props.wrapAround)return;if(e>=a["default"].Children.count(this.props.children))return this.props.beforeSlide(this.state.currentSlide,0),this.setState({currentSlide:0},function(){t.animateSlide(null,null,t.getTargetLeft(null,e),function(){t.animateSlide(null,.01),t.props.afterSlide(0),t.resetAutoplay(),t.setExternalData()})});var n=a["default"].Children.count(this.props.children)-this.state.slidesToScroll;return this.props.beforeSlide(this.state.currentSlide,n),this.setState({currentSlide:n},function(){t.animateSlide(null,null,t.getTargetLeft(null,e),function(){t.animateSlide(null,.01),t.props.afterSlide(n),t.resetAutoplay(),t.setExternalData()})})}this.props.beforeSlide(this.state.currentSlide,e),this.setState({currentSlide:e},function(){t.animateSlide(),this.props.afterSlide(e),t.resetAutoplay(),t.setExternalData()})},nextSlide:function(){var e=a["default"].Children.count(this.props.children),t=this.props.slidesToShow;if("auto"===this.props.slidesToScroll&&(t=this.state.slidesToScroll),!(this.state.currentSlide>=e-t)||this.props.wrapAround)if(this.props.wrapAround)this.goToSlide(this.state.currentSlide+this.state.slidesToScroll);else{if(1!==this.props.slideWidth)return this.goToSlide(this.state.currentSlide+this.state.slidesToScroll);this.goToSlide(Math.min(this.state.currentSlide+this.state.slidesToScroll,e-t))}},previousSlide:function(){this.state.currentSlide<=0&&!this.props.wrapAround||(this.props.wrapAround?this.goToSlide(this.state.currentSlide-this.state.slidesToScroll):this.goToSlide(Math.max(0,this.state.currentSlide-this.state.slidesToScroll)))},animateSlide:function(e,t,n,i){this.tweenState(this.props.vertical?"top":"left",{easing:e||u["default"].easingTypes[this.props.easing],duration:t||this.props.speed,endValue:n||this.getTargetLeft(),onEnd:i||null})},getTargetLeft:function(e,t){var n,i=t||this.state.currentSlide;switch(this.props.cellAlign){case"left":n=0,n-=this.props.cellSpacing*i;break;case"center":n=(this.state.frameWidth-this.state.slideWidth)/2,n-=this.props.cellSpacing*i;break;case"right":n=this.state.frameWidth-this.state.slideWidth,n-=this.props.cellSpacing*i}var r=this.state.slideWidth*i,o=this.state.currentSlide>0&&i+this.state.slidesToScroll>=this.state.slideCount;return o&&1!==this.props.slideWidth&&!this.props.wrapAround&&"auto"===this.props.slidesToScroll&&(r=this.state.slideWidth*this.state.slideCount-this.state.frameWidth,n=0,n-=this.props.cellSpacing*(this.state.slideCount-1)),n-=e||0,(r-n)*-1},bindEvents:function(){var e=this;m["default"].canUseDOM&&(y(window,"resize",e.onResize),y(document,"readystatechange",e.onReadyStateChange))},onResize:function(){this.setDimensions()},onReadyStateChange:function(){this.setDimensions()},unbindEvents:function(){var e=this;m["default"].canUseDOM&&(v(window,"resize",e.onResize),v(document,"readystatechange",e.onReadyStateChange))},formatChildren:function(e){var t=this,n=this.props.vertical?this.getTweeningValue("top"):this.getTweeningValue("left");return a["default"].Children.map(e,function(e,i){return a["default"].createElement("li",{className:"slider-slide",style:t.getSlideStyles(i,n),key:i},e)})},setInitialDimensions:function(){var e,t,n,i=this;e=this.props.vertical?this.props.initialSlideHeight||0:this.props.initialSlideWidth||0,n=this.props.initialSlideHeight?this.props.initialSlideHeight*this.props.slidesToShow:0,t=n+this.props.cellSpacing*(this.props.slidesToShow-1),this.setState({slideHeight:n,frameWidth:this.props.vertical?t:"100%",slideCount:a["default"].Children.count(this.props.children),slideWidth:e},function(){i.setLeft(),i.setExternalData()})},setDimensions:function(e){e=e||this.props;var t,n,i,r,o,a,s,l=this;n=e.slidesToScroll,r=this.refs.frame,i=r.childNodes[0].childNodes[0],i?(i.style.height="auto",s=this.props.vertical?i.offsetHeight*e.slidesToShow:i.offsetHeight):s=100,t="number"!=typeof e.slideWidth?parseInt(e.slideWidth):e.vertical?s/e.slidesToShow*e.slideWidth:r.offsetWidth/e.slidesToShow*e.slideWidth,e.vertical||(t-=e.cellSpacing*((100-100/e.slidesToShow)/100)),a=s+e.cellSpacing*(e.slidesToShow-1),o=e.vertical?a:r.offsetWidth,"auto"===e.slidesToScroll&&(n=Math.floor(o/(t+e.cellSpacing))),this.setState({slideHeight:s,frameWidth:o,slideWidth:t,slidesToScroll:n,left:e.vertical?0:this.getTargetLeft(),top:e.vertical?this.getTargetLeft():0},function(){l.setLeft()})},setLeft:function(){this.setState({left:this.props.vertical?0:this.getTargetLeft(),top:this.props.vertical?this.getTargetLeft():0})},setExternalData:function(){this.props.data&&this.props.data()},getListStyles:function(){var e=this.state.slideWidth*a["default"].Children.count(this.props.children),t=this.props.cellSpacing*a["default"].Children.count(this.props.children),n="translate3d("+this.getTweeningValue("left")+"px, "+this.getTweeningValue("top")+"px, 0)";return{transform:n,WebkitTransform:n,msTransform:"translate("+this.getTweeningValue("left")+"px, "+this.getTweeningValue("top")+"px)",position:"relative",display:"block",margin:this.props.vertical?this.props.cellSpacing/2*-1+"px 0px":"0px "+this.props.cellSpacing/2*-1+"px",padding:0,height:this.props.vertical?e+t:this.state.slideHeight,width:this.props.vertical?"auto":e+t,cursor:this.state.dragging===!0?"pointer":"inherit",boxSizing:"border-box",MozBoxSizing:"border-box"}},getFrameStyles:function(){return{position:"relative",display:"block",overflow:this.props.frameOverflow,height:this.props.vertical?this.state.frameWidth||"initial":"auto",margin:this.props.framePadding,padding:0,transform:"translate3d(0, 0, 0)",WebkitTransform:"translate3d(0, 0, 0)",msTransform:"translate(0, 0)",boxSizing:"border-box",MozBoxSizing:"border-box"}},getSlideStyles:function(e,t){var n=this.getSlideTargetPosition(e,t);return{position:"absolute",left:this.props.vertical?0:n,top:this.props.vertical?n:0,display:this.props.vertical?"block":"inline-block",listStyleType:"none",verticalAlign:"top",width:this.props.vertical?"100%":this.state.slideWidth,height:"auto",boxSizing:"border-box",MozBoxSizing:"border-box",marginLeft:this.props.vertical?"auto":this.props.cellSpacing/2,marginRight:this.props.vertical?"auto":this.props.cellSpacing/2,marginTop:this.props.vertical?this.props.cellSpacing/2:"auto",marginBottom:this.props.vertical?this.props.cellSpacing/2:"auto"}},getSlideTargetPosition:function(e,t){var n=this.state.frameWidth/this.state.slideWidth,i=(this.state.slideWidth+this.props.cellSpacing)*e,r=(this.state.slideWidth+this.props.cellSpacing)*n*-1;if(this.props.wrapAround){var o=Math.ceil(t/this.state.slideWidth);if(this.state.slideCount-o<=e)return(this.state.slideWidth+this.props.cellSpacing)*(this.state.slideCount-e)*-1;var a=Math.ceil((Math.abs(t)-Math.abs(r))/this.state.slideWidth);if(1!==this.state.slideWidth&&(a=Math.ceil((Math.abs(t)-this.state.slideWidth)/this.state.slideWidth)),e<=a-1)return(this.state.slideWidth+this.props.cellSpacing)*(this.state.slideCount+e)}return i},getSliderStyles:function(){return{position:"relative",display:"block",width:this.props.width,height:"auto",boxSizing:"border-box",MozBoxSizing:"border-box",visibility:this.state.slideWidth?"visible":"hidden"}},getStyleTagStyles:function(){return".slider-slide > img {width: 100%; display: block;}"},getDecoratorStyles:function(e){switch(e){case"TopLeft":return{position:"absolute",top:0,left:0};case"TopCenter":return{position:"absolute",top:0,left:"50%",transform:"translateX(-50%)",WebkitTransform:"translateX(-50%)",msTransform:"translateX(-50%)"};case"TopRight":return{position:"absolute",top:0,right:0};case"CenterLeft":return{position:"absolute",top:"50%",left:0,transform:"translateY(-50%)",WebkitTransform:"translateY(-50%)",msTransform:"translateY(-50%)"};case"CenterCenter":return{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",WebkitTransform:"translate(-50%, -50%)",msTransform:"translate(-50%, -50%)"};case"CenterRight":return{position:"absolute",top:"50%",right:0,transform:"translateY(-50%)",WebkitTransform:"translateY(-50%)",msTransform:"translateY(-50%)"};case"BottomLeft":return{position:"absolute",bottom:0,left:0};case"BottomCenter":return{position:"absolute",bottom:0,left:"50%",transform:"translateX(-50%)",WebkitTransform:"translateX(-50%)",msTransform:"translateX(-50%)"};case"BottomRight":return{position:"absolute",bottom:0,right:0};default:return{position:"absolute",top:0,left:0}}}});g.ControllerMixin={getInitialState:function(){return{carousels:{}}},setCarouselData:function(e){var t=this.state.carousels;t[e]=this.refs[e],this.setState({carousels:t})}},t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=[{component:o["default"].createClass({displayName:"component",render:function(){return o["default"].createElement("button",{style:this.getButtonStyles(0===this.props.currentSlide&&!this.props.wrapAround),onClick:this.handleClick},"PREV")},handleClick:function(e){e.preventDefault(),this.props.previousSlide()},getButtonStyles:function(e){return{border:0,background:"rgba(0,0,0,0.4)",color:"white",padding:10,outline:0,opacity:e?.3:1,cursor:"pointer"}}}),position:"CenterLeft"},{component:o["default"].createClass({displayName:"component",render:function(){return o["default"].createElement("button",{style:this.getButtonStyles(this.props.currentSlide+this.props.slidesToScroll>=this.props.slideCount&&!this.props.wrapAround),onClick:this.handleClick},"NEXT")},handleClick:function(e){e.preventDefault(),this.props.nextSlide()},getButtonStyles:function(e){return{border:0,background:"rgba(0,0,0,0.4)",color:"white",padding:10,outline:0,opacity:e?.3:1,cursor:"pointer"}}}),position:"CenterRight"},{component:o["default"].createClass({displayName:"component",render:function(){var e=this,t=this.getIndexes(e.props.slideCount,e.props.slidesToScroll);return o["default"].createElement("ul",{style:e.getListStyles()},t.map(function(t){return o["default"].createElement("li",{style:e.getListItemStyles(),key:t},o["default"].createElement("button",{style:e.getButtonStyles(e.props.currentSlide===t),onClick:e.props.goToSlide.bind(null,t)},"\u2022"))}))},getIndexes:function(e,t){for(var n=[],i=0;i<e;i+=t)n.push(i);return n},getListStyles:function(){return{position:"relative",margin:0,top:-10,padding:0}},getListItemStyles:function(){return{listStyleType:"none",display:"inline-block"}},getButtonStyles:function(e){return{border:0,background:"transparent",color:"black",cursor:"pointer",padding:10,outline:0,fontSize:24,opacity:e?1:.5}}}),position:"BottomCenter"}];t["default"]=a,e.exports=t["default"]},function(e,t,n){var i,r,o;!function(n,a){"use strict";"object"==typeof e&&"object"==typeof e.exports?e.exports=a():(r=[],i=a,o="function"==typeof i?i.apply(t,r):i,!(void 0!==o&&(e.exports=o)))}(this,function(){"use strict";function e(e,t){return null!=e&&Object.prototype.hasOwnProperty.call(e,t)}function t(t){if(!t)return!0;if(l(t)&&0===t.length)return!0;if("string"!=typeof t){for(var n in t)if(e(t,n))return!1;return!0}return!1}function n(e){return s.call(e)}function i(e){return"object"==typeof e&&"[object Object]"===n(e)}function r(e){return"boolean"==typeof e||"[object Boolean]"===n(e)}function o(e){var t=parseInt(e);return t.toString()===e?t:e}function a(n){function a(t,i){if(n.includeInheritedProps||"number"==typeof i&&Array.isArray(t)||e(t,i))return t[i]}function s(e,t,n,i){if("number"==typeof t&&(t=[t]),!t||0===t.length)return e;if("string"==typeof t)return s(e,t.split(".").map(o),n,i);var r=t[0],l=a(e,r);return 1===t.length?(void 0!==l&&i||(e[r]=n),l):(void 0===l&&("number"==typeof t[1]?e[r]=[]:e[r]={}),s(e[r],t.slice(1),n,i))}n=n||{};var u=function(e){return Object.keys(u).reduce(function(t,n){return"create"===n?t:("function"==typeof u[n]&&(t[n]=u[n].bind(u,e)),t)},{})};return u.has=function(t,i){if("number"==typeof i?i=[i]:"string"==typeof i&&(i=i.split(".")),!i||0===i.length)return!!t;for(var r=0;r<i.length;r++){var a=o(i[r]);if(!("number"==typeof a&&l(t)&&a<t.length||(n.includeInheritedProps?a in Object(t):e(t,a))))return!1;t=t[a]}return!0},u.ensureExists=function(e,t,n){return s(e,t,n,!0)},u.set=function(e,t,n,i){return s(e,t,n,i)},u.insert=function(e,t,n,i){var r=u.get(e,t);i=~~i,l(r)||(r=[],u.set(e,t,r)),r.splice(i,0,n)},u.empty=function(n,o){if(!t(o)&&null!=n){var a,s;if(a=u.get(n,o)){if("string"==typeof a)return u.set(n,o,"");if(r(a))return u.set(n,o,!1);if("number"==typeof a)return u.set(n,o,0);if(l(a))a.length=0;else{if(!i(a))return u.set(n,o,null);for(s in a)e(a,s)&&delete a[s]}}}},u.push=function(e,t){var n=u.get(e,t);l(n)||(n=[],u.set(e,t,n)),n.push.apply(n,Array.prototype.slice.call(arguments,2))},u.coalesce=function(e,t,n){for(var i,r=0,o=t.length;r<o;r++)if(void 0!==(i=u.get(e,t[r])))return i;return n},u.get=function(e,t,n){if("number"==typeof t&&(t=[t]),!t||0===t.length)return e;if(null==e)return n;if("string"==typeof t)return u.get(e,t.split("."),n);var i=o(t[0]),r=a(e,i);return void 0===r?n:1===t.length?r:u.get(e[i],t.slice(1),n)},u.del=function(e,n){if("number"==typeof n&&(n=[n]),null==e)return e;if(t(n))return e;if("string"==typeof n)return u.del(e,n.split("."));var i=o(n[0]),r=a(e,i);if(null==r)return r;if(1===n.length)l(e)?e.splice(i,1):delete e[i];else if(void 0!==e[i])return u.del(e[i],n.slice(1));return e},u}var s=Object.prototype.toString,l=Array.isArray||function(e){return"[object Array]"===s.call(e)},u=a();return u.create=a,u.withInheritedProps=a({includeInheritedProps:!0}),u})},function(e,t,n){/*! * object.omit <https://github.com/jonschlinkert/object.omit> * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ "use strict";var i=n(330),r=n(328);e.exports=function(e,t){if(!i(e))return{};t=[].concat.apply([],[].slice.call(arguments,1));var n,o=t[t.length-1],a={};"function"==typeof o&&(n=t.pop());var s="function"==typeof n;return t.length||s?(r(e,function(i,r){t.indexOf(r)===-1&&(s?n(i,r,e)&&(a[r]=i):a[r]=i)}),a):e}},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){function n(){r&&(clearTimeout(r),r=null)}function i(){n(),r=setTimeout(e,t)}var r=void 0;return i.clear=n,i}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=i(o),s=n(9),l=i(s),u=n(277),c=i(u),d=n(344),f=i(d),p=n(343),h=i(p),m=a["default"].createClass({displayName:"Align",propTypes:{childrenProps:o.PropTypes.object,align:o.PropTypes.object.isRequired,target:o.PropTypes.func,onAlign:o.PropTypes.func,monitorBufferTime:o.PropTypes.number,monitorWindowResize:o.PropTypes.bool,disabled:o.PropTypes.bool,children:o.PropTypes.any},getDefaultProps:function(){return{target:function(){return window},onAlign:function(){},monitorBufferTime:50,monitorWindowResize:!1,disabled:!1}},componentDidMount:function(){var e=this.props;this.forceAlign(),!e.disabled&&e.monitorWindowResize&&this.startMonitorWindowResize()},componentDidUpdate:function(e){var t=!1,n=this.props;if(!n.disabled)if(e.disabled||e.align!==n.align)t=!0;else{var i=e.target(),r=n.target();(0,h["default"])(i)&&(0,h["default"])(r)?t=!1:i!==r&&(t=!0)}t&&this.forceAlign(),n.monitorWindowResize&&!n.disabled?this.startMonitorWindowResize():this.stopMonitorWindowResize()},componentWillUnmount:function(){this.stopMonitorWindowResize()},startMonitorWindowResize:function(){this.resizeHandler||(this.bufferMonitor=r(this.forceAlign,this.props.monitorBufferTime),this.resizeHandler=(0,f["default"])(window,"resize",this.bufferMonitor))},stopMonitorWindowResize:function(){this.resizeHandler&&(this.bufferMonitor.clear(),this.resizeHandler.remove(),this.resizeHandler=null)},forceAlign:function(){var e=this.props;if(!e.disabled){var t=l["default"].findDOMNode(this);e.onAlign(t,(0,c["default"])(t,e.target(),e.align))}},render:function(){var e=this.props,t=e.childrenProps,n=e.children,i=a["default"].Children.only(n);if(t){var r={};for(var o in t)t.hasOwnProperty(o)&&(r[o]=this.props[t[o]]);return a["default"].cloneElement(i,r)}return i}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(341),o=i(r);t["default"]=o["default"],e.exports=t["default"]},function(e,t){"use strict";function n(e){return null!=e&&e==e.window}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){var i=l["default"].unstable_batchedUpdates?function(e){l["default"].unstable_batchedUpdates(n,e)}:n;return(0,a["default"])(e,t,i)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var o=n(40),a=i(o),s=n(9),l=i(s);e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=e.children;return l["default"].isValidElement(t)&&!t.key?l["default"].cloneElement(t,{key:h}):t}function a(){}Object.defineProperty(t,"__esModule",{value:!0});var s=n(1),l=i(s),u=n(347),c=n(346),d=i(c),f=n(107),p=i(f),h="rc_animate_"+Date.now(),m=l["default"].createClass({displayName:"Animate",propTypes:{component:l["default"].PropTypes.any,animation:l["default"].PropTypes.object,transitionName:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.object]),transitionEnter:l["default"].PropTypes.bool,transitionAppear:l["default"].PropTypes.bool,exclusive:l["default"].PropTypes.bool,transitionLeave:l["default"].PropTypes.bool,onEnd:l["default"].PropTypes.func,onEnter:l["default"].PropTypes.func,onLeave:l["default"].PropTypes.func,onAppear:l["default"].PropTypes.func,showProp:l["default"].PropTypes.string},getDefaultProps:function(){return{animation:{},component:"span",transitionEnter:!0,transitionLeave:!0,transitionAppear:!1,onEnd:a,onEnter:a,onLeave:a,onAppear:a}},getInitialState:function(){return this.currentlyAnimatingKeys={},this.keysToEnter=[],this.keysToLeave=[],{children:(0,u.toArrayChildren)(o(this.props))}},componentDidMount:function(){var e=this,t=this.props.showProp,n=this.state.children;t&&(n=n.filter(function(e){return!!e.props[t]})),n.forEach(function(t){t&&e.performAppear(t.key)})},componentWillReceiveProps:function(e){var t=this;this.nextProps=e;var n=(0,u.toArrayChildren)(o(e)),i=this.props;i.exclusive&&Object.keys(this.currentlyAnimatingKeys).forEach(function(e){t.stop(e)});var a=i.showProp,s=this.currentlyAnimatingKeys,c=i.exclusive?(0,u.toArrayChildren)(o(i)):this.state.children,d=[];a?(c.forEach(function(e){var t=e&&(0,u.findChildInChildrenByKey)(n,e.key),i=void 0;i=t&&t.props[a]||!e.props[a]?t:l["default"].cloneElement(t||e,r({},a,!0)),i&&d.push(i)}),n.forEach(function(e){e&&(0,u.findChildInChildrenByKey)(c,e.key)||d.push(e)})):d=(0,u.mergeChildren)(c,n),this.setState({children:d}),n.forEach(function(e){var n=e&&e.key;if(!e||!s[n]){var i=e&&(0,u.findChildInChildrenByKey)(c,n);if(a){var r=e.props[a];if(i){var o=(0,u.findShownChildInChildrenByKey)(c,n,a);!o&&r&&t.keysToEnter.push(n)}else r&&t.keysToEnter.push(n)}else i||t.keysToEnter.push(n)}}),c.forEach(function(e){var i=e&&e.key;if(!e||!s[i]){var r=e&&(0,u.findChildInChildrenByKey)(n,i);if(a){var o=e.props[a];if(r){var l=(0,u.findShownChildInChildrenByKey)(n,i,a);!l&&o&&t.keysToLeave.push(i)}else o&&t.keysToLeave.push(i)}else r||t.keysToLeave.push(i)}})},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performEnter:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillEnter(this.handleDoneAdding.bind(this,e,"enter")))},performAppear:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillAppear(this.handleDoneAdding.bind(this,e,"appear")))},handleDoneAdding:function(e,t){var n=this.props;if(delete this.currentlyAnimatingKeys[e],!n.exclusive||n===this.nextProps){var i=(0,u.toArrayChildren)(o(n));this.isValidChildByKey(i,e)?"appear"===t?p["default"].allowAppearCallback(n)&&(n.onAppear(e),n.onEnd(e,!0)):p["default"].allowEnterCallback(n)&&(n.onEnter(e),n.onEnd(e,!0)):this.performLeave(e)}},performLeave:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillLeave(this.handleDoneLeaving.bind(this,e)))},handleDoneLeaving:function(e){var t=this.props;if(delete this.currentlyAnimatingKeys[e],!t.exclusive||t===this.nextProps){var n=(0,u.toArrayChildren)(o(t));if(this.isValidChildByKey(n,e))this.performEnter(e);else{var i=function(){p["default"].allowLeaveCallback(t)&&(t.onLeave(e),t.onEnd(e,!1))};this.isMounted()&&!(0,u.isSameChildren)(this.state.children,n,t.showProp)?this.setState({children:n},i):i()}}},isValidChildByKey:function(e,t){var n=this.props.showProp;return n?(0,u.findShownChildInChildrenByKey)(e,t,n):(0,u.findChildInChildrenByKey)(e,t)},stop:function(e){delete this.currentlyAnimatingKeys[e];var t=this.refs[e];t&&t.stop()},render:function(){var e=this.props;this.nextProps=e;var t=this.state.children,n=null;t&&(n=t.map(function(t){if(null===t||void 0===t)return t;if(!t.key)throw new Error("must set key for <rc-animate> children");return l["default"].createElement(d["default"],{key:t.key,ref:t.key,animation:e.animation,transitionName:e.transitionName,transitionEnter:e.transitionEnter,transitionAppear:e.transitionAppear,transitionLeave:e.transitionLeave},t)}));var i=e.component;if(i){var r=e;return"string"==typeof i&&(r={className:e.className,style:e.style}),l["default"].createElement(i,r,n)}return n[0]||null}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r="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},o=n(1),a=i(o),s=n(9),l=i(s),u=n(102),c=i(u),d=n(107),f=i(d),p={enter:"transitionEnter",appear:"transitionAppear",leave:"transitionLeave"},h=a["default"].createClass({displayName:"AnimateChild",propTypes:{children:a["default"].PropTypes.any},componentWillUnmount:function(){this.stop()},componentWillEnter:function(e){f["default"].isEnterSupported(this.props)?this.transition("enter",e):e()},componentWillAppear:function(e){f["default"].isAppearSupported(this.props)?this.transition("appear",e):e()},componentWillLeave:function(e){f["default"].isLeaveSupported(this.props)?this.transition("leave",e):e()},transition:function(e,t){var n=this,i=l["default"].findDOMNode(this),o=this.props,a=o.transitionName,s="object"===("undefined"==typeof a?"undefined":r(a));this.stop();var d=function(){n.stopper=null,t()};if((u.isCssAnimationSupported||!o.animation[e])&&a&&o[p[e]]){var f=s?a[e]:a+"-"+e,h=f+"-active";s&&a[e+"Active"]&&(h=a[e+"Active"]),this.stopper=(0,c["default"])(i,{name:f,active:h},d)}else this.stopper=o.animation[e](i,d)},stop:function(){var e=this.stopper;e&&(this.stopper=null,e.stop())},render:function(){return this.props.children}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=[];return d["default"].Children.forEach(e,function(e){t.push(e)}),t}function o(e,t){var n=null;return e&&e.forEach(function(e){n||e&&e.key===t&&(n=e)}),n}function a(e,t,n){var i=null;return e&&e.forEach(function(e){if(e&&e.key===t&&e.props[n]){if(i)throw new Error("two child with same key for <rc-animate> children");i=e}}),i}function s(e,t,n){var i=0;return e&&e.forEach(function(e){i||(i=e&&e.key===t&&!e.props[n])}),i}function l(e,t,n){var i=e.length===t.length;return i&&e.forEach(function(e,r){var o=t[r];e&&o&&(e&&!o||!e&&o?i=!1:e.key!==o.key?i=!1:n&&e.props[n]!==o.props[n]&&(i=!1))}),i}function u(e,t){var n=[],i={},r=[];return e.forEach(function(e){e&&o(t,e.key)?r.length&&(i[e.key]=r,r=[]):r.push(e)}),t.forEach(function(e){e&&i.hasOwnProperty(e.key)&&(n=n.concat(i[e.key])),n.push(e)}),n=n.concat(r)}Object.defineProperty(t,"__esModule",{value:!0}),t.toArrayChildren=r,t.findChildInChildrenByKey=o,t.findShownChildInChildrenByKey=a,t.findHiddenChildInChildrenByKey=s,t.isSameChildren=l,t.mergeChildren=u;var c=n(1),d=i(c)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){for(var n=Object.getOwnPropertyNames(t),i=0;i<n.length;i++){var r=n[i],o=Object.getOwnPropertyDescriptor(t,r);o&&o.configurable&&void 0===e[r]&&Object.defineProperty(e,r,o)}return e}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):r(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},c=n(1),d=i(c),f=n(404),p=i(f),h=n(5),m=i(h),y=function(e){function t(n){a(this,t);var i=s(this,e.call(this,n));i.handleFocus=function(e){i.setState({focus:!0}),i.props.onFocus(e)},i.handleBlur=function(e){i.setState({focus:!1}),i.props.onBlur(e)},i.handleChange=function(e){"checked"in i.props||i.setState({checked:e.target.checked}),i.props.onChange({target:u({},i.props,{checked:e.target.checked}),stopPropagation:function(){e.stopPropagation()},preventDefault:function(){e.preventDefault()}})};var r=!1;return r="checked"in n?n.checked:n.defaultChecked,i.state={checked:r,focus:!1},i}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"checked"in e&&this.setState({checked:e.checked})},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return p["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=u({},this.props);delete t.defaultChecked;var n=this.state,i=t.prefixCls,r=n.checked;"boolean"==typeof r&&(r=r?1:0);var a=(0,m["default"])((e={},o(e,t.className,!!t.className),o(e,i,1),o(e,i+"-checked",r),o(e,i+"-checked-"+r,!!r),o(e,i+"-focused",n.focus),o(e,i+"-disabled",t.disabled),e));return d["default"].createElement("span",{className:a,style:t.style},d["default"].createElement("span",{className:i+"-inner"}),d["default"].createElement("input",{name:t.name,type:t.type,readOnly:t.readOnly,disabled:t.disabled,tabIndex:t.tabIndex,className:i+"-input",checked:!!r,onClick:this.props.onClick,onFocus:this.handleFocus,onBlur:this.handleBlur,onChange:this.handleChange}))},t}(d["default"].Component);y.propTypes={name:d["default"].PropTypes.string,prefixCls:d["default"].PropTypes.string,style:d["default"].PropTypes.object,type:d["default"].PropTypes.string,className:d["default"].PropTypes.string,defaultChecked:d["default"].PropTypes.oneOfType([d["default"].PropTypes.number,d["default"].PropTypes.bool]),checked:d["default"].PropTypes.oneOfType([d["default"].PropTypes.number,d["default"].PropTypes.bool]),onFocus:d["default"].PropTypes.func,onBlur:d["default"].PropTypes.func,onChange:d["default"].PropTypes.func,onClick:d["default"].PropTypes.func},y.defaultProps={prefixCls:"rc-checkbox",style:{},type:"checkbox",className:"",defaultChecked:!1,onFocus:function(){},onBlur:function(){},onChange:function(){}},t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e){var t=e;return Array.isArray(t)||(t=t?[t]:[]),t}Object.defineProperty(t,"__esModule",{value:!0});var s=n(1),l=i(s),u=n(350),c=i(u),d=n(353),f=i(d),p=n(5),h=i(p),m=l["default"].createClass({displayName:"Collapse",propTypes:{children:s.PropTypes.any,prefixCls:s.PropTypes.string,activeKey:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.arrayOf(s.PropTypes.string)]),defaultActiveKey:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.arrayOf(s.PropTypes.string)]),openAnimation:s.PropTypes.object,onChange:s.PropTypes.func,accordion:s.PropTypes.bool,className:s.PropTypes.string,style:s.PropTypes.object},statics:{Panel:c["default"]},getDefaultProps:function(){return{prefixCls:"rc-collapse",onChange:function(){},accordion:!1}},getInitialState:function(){var e=this.props,t=e.activeKey,n=e.defaultActiveKey,i=n;return"activeKey"in this.props&&(i=t),{openAnimation:this.props.openAnimation||(0,f["default"])(this.props.prefixCls),activeKey:a(i)}},componentWillReceiveProps:function(e){"activeKey"in e&&this.setState({activeKey:a(e.activeKey)}),"openAnimation"in e&&this.setState({openAnimation:e.openAnimation})},onClickItem:function(e){var t=this;return function(){var n=t.state.activeKey;if(t.props.accordion)n=n[0]===e?[]:[e];else{n=[].concat(o(n));var i=n.indexOf(e),r=i>-1;r?n.splice(i,1):n.push(e)}t.setActiveKey(n)}},getItems:function(){var e=this,t=this.state.activeKey,n=this.props,i=n.prefixCls,r=n.accordion;return s.Children.map(this.props.children,function(n,o){var a=n.key||String(o),s=n.props.header,u=!1;u=r?t[0]===a:t.indexOf(a)>-1;var c={key:a,header:s,isActive:u,prefixCls:i,openAnimation:e.state.openAnimation,children:n.props.children,onItemClick:e.onClickItem(a).bind(e)};return l["default"].cloneElement(n,c)})},setActiveKey:function(e){"activeKey"in this.props||this.setState({activeKey:e}),this.props.onChange(this.props.accordion?e[0]:e)},render:function(){var e,t=this.props,n=t.prefixCls,i=t.className,o=t.style,a=(0,h["default"])((e={},r(e,n,!0),r(e,i,!!i),e));return l["default"].createElement("div",{className:a,style:o},this.getItems())}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=i(o),s=n(5),l=i(s),u=n(351),c=i(u),d=n(45),f=i(d),p=a["default"].createClass({displayName:"CollapsePanel",propTypes:{className:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.object]),children:o.PropTypes.any,openAnimation:o.PropTypes.object,prefixCls:o.PropTypes.string,header:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.node]),isActive:o.PropTypes.bool,onItemClick:o.PropTypes.func},getDefaultProps:function(){return{isActive:!1,onItemClick:function(){}}},handleItemClick:function(){this.props.onItemClick()},render:function(){var e,t=this.props,n=t.className,i=t.prefixCls,o=t.header,s=t.children,u=t.isActive,d=i+"-header",p=(0,l["default"])((e={},r(e,i+"-item",!0),r(e,i+"-item-active",u),r(e,n,n),e));return a["default"].createElement("div",{className:p},a["default"].createElement("div",{className:d,onClick:this.handleItemClick,role:"tab","aria-expanded":u},a["default"].createElement("i",{className:"arrow"}),o),a["default"].createElement(f["default"],{showProp:"isActive",exclusive:!0,component:"",animation:this.props.openAnimation},a["default"].createElement(c["default"],{prefixCls:i,isActive:u},s)))}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=i(o),s=n(5),l=i(s),u=a["default"].createClass({displayName:"PanelContent",propTypes:{prefixCls:o.PropTypes.string,isActive:o.PropTypes.bool,children:o.PropTypes.any},shouldComponentUpdate:function(e){return this.props.isActive||e.isActive},render:function(){var e;if(this._isActived=this._isActived||this.props.isActive,!this._isActived)return null;var t=this.props,n=t.prefixCls,i=t.isActive,o=t.children,s=(0,l["default"])((e={},r(e,n+"-content",!0),r(e,n+"-content-active",i),r(e,n+"-content-inactive",!i),e));return a["default"].createElement("div",{className:s,role:"tabpanel"},a["default"].createElement("div",{className:n+"-content-box"},o))}});t["default"]=u,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(349),o=i(r);t["default"]=o["default"],e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n,i){var r=void 0;return(0,s["default"])(e,n,{start:function(){t?(r=e.offsetHeight,e.style.height=0):e.style.height=e.offsetHeight+"px"},active:function(){e.style.height=(t?r:0)+"px"},end:function(){e.style.height="",i()}})}function o(e){return{enter:function(t,n){return r(t,!0,e+"-anim",n)},leave:function(t,n){return r(t,!1,e+"-anim",n)}}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(102),s=i(a);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}function o(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],i="scroll"+(t?"Top":"Left");if("number"!=typeof n){var r=e.document;n=r.documentElement[i],"number"!=typeof n&&(n=r.body[i])}return n}function a(e,t){var n=e.style;["Webkit","Moz","Ms","ms"].forEach(function(e){n[e+"TransformOrigin"]=t}),n.transformOrigin=t}function s(e){var t=e.getBoundingClientRect(),n={left:t.left,top:t.top},i=e.ownerDocument,r=i.defaultView||i.parentWindow;return n.left+=o(r),n.top+=o(r,!0),n}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=i(l),c=n(9),d=i(c),f=n(356),p=i(f),h=n(45),m=i(h),y=n(355),v=i(y),g=n(358),b=i(g),M=n(10),T=i(M),x=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},C=0,_=0,w=u["default"].createClass({displayName:"Dialog",getDefaultProps:function(){return{afterClose:r,className:"",mask:!0,visible:!1,keyboard:!0,closable:!0,maskClosable:!0,prefixCls:"rc-dialog",onClose:r}},componentWillMount:function(){this.titleId="rcDialogTitle"+C++},componentDidMount:function(){this.componentDidUpdate({})},componentDidUpdate:function(e){var t=this.props,n=this.props.mousePosition;if(t.visible){if(!e.visible){this.lastOutSideFocusNode=document.activeElement,this.addScrollingEffect(),this.refs.wrap.focus();var i=d["default"].findDOMNode(this.refs.dialog);if(n){var r=s(i);a(i,n.x-r.left+"px "+(n.y-r.top)+"px")}else a(i,"")}}else if(e.visible&&t.mask&&this.lastOutSideFocusNode){try{this.lastOutSideFocusNode.focus()}catch(o){this.lastOutSideFocusNode=null}this.lastOutSideFocusNode=null}},onAnimateLeave:function(){this.refs.wrap&&(this.refs.wrap.style.display="none"),this.removeScrollingEffect(),this.props.afterClose()},onMaskClick:function(e){e.target===e.currentTarget&&this.props.maskClosable&&this.close(e)},onKeyDown:function(e){var t=this.props;if(t.keyboard&&e.keyCode===p["default"].ESC&&this.close(e),t.visible&&e.keyCode===p["default"].TAB){var n=document.activeElement,i=this.refs.wrap,r=this.refs.sentinel;e.shiftKey?n===i&&r.focus():n===this.refs.sentinel&&i.focus()}},getDialogElement:function(){var e=this.props,t=e.closable,n=e.prefixCls,i={};void 0!==e.width&&(i.width=e.width),void 0!==e.height&&(i.height=e.height);var r=void 0;e.footer&&(r=u["default"].createElement("div",{className:n+"-footer",ref:"footer"},e.footer));var o=void 0;e.title&&(o=u["default"].createElement("div",{className:n+"-header",ref:"header"},u["default"].createElement("div",{className:n+"-title",id:this.titleId},e.title)));var a=void 0;t&&(a=u["default"].createElement("button",{onClick:this.close,"aria-label":"Close",className:n+"-close"},u["default"].createElement("span",{className:n+"-close-x"})));var s=(0,T["default"])({},e.style,i),l=this.getTransitionName(),c=u["default"].createElement(v["default"],{role:"document",ref:"dialog",style:s,className:n+" "+(e.className||""),visible:e.visible},u["default"].createElement("div",{className:n+"-content"},a,o,u["default"].createElement("div",x({className:n+"-body",style:e.bodyStyle,ref:"body"},e.bodyProps),e.children),r),u["default"].createElement("div",{tabIndex:0,ref:"sentinel",style:{width:0,height:0,overflow:"hidden"}},"sentinel"));return u["default"].createElement(m["default"],{key:"dialog",showProp:"visible",onLeave:this.onAnimateLeave,transitionName:l,component:"",transitionAppear:!0},c)},getZIndexStyle:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getWrapStyle:function(){return(0,T["default"])({},this.getZIndexStyle(),this.props.wrapStyle)},getMaskStyle:function(){return(0,T["default"])({},this.getZIndexStyle(),this.props.maskStyle)},getMaskElement:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=u["default"].createElement(v["default"],{style:this.getMaskStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=u["default"].createElement(m["default"],{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},getMaskTransitionName:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getTransitionName:function(){var e=this.props,t=e.transitionName,n=e.animation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getElement:function(e){return this.refs[e]},setScrollbar:function(){this.bodyIsOverflowing&&void 0!==this.scrollbarWidth&&(document.body.style.paddingRight=this.scrollbarWidth+"px")},addScrollingEffect:function(){_++,1===_&&(this.checkScrollbar(),this.setScrollbar(),document.body.style.overflow="hidden")},removeScrollingEffect:function(){_--,0===_&&(document.body.style.overflow="",this.resetScrollbar())},close:function(e){this.props.onClose(e)},checkScrollbar:function(){var e=window.innerWidth;if(!e){var t=document.documentElement.getBoundingClientRect();e=t.right-Math.abs(t.left)}this.bodyIsOverflowing=document.body.clientWidth<e,this.bodyIsOverflowing&&(this.scrollbarWidth=(0,b["default"])())},resetScrollbar:function(){document.body.style.paddingRight=""},adjustDialog:function(){if(this.refs.wrap&&void 0!==this.scrollbarWidth){var e=this.refs.wrap.scrollHeight>document.documentElement.clientHeight;this.refs.wrap.style.paddingLeft=(!this.bodyIsOverflowing&&e?this.scrollbarWidth:"")+"px",this.refs.wrap.style.paddingRight=(this.bodyIsOverflowing&&!e?this.scrollbarWidth:"")+"px"}},resetAdjustments:function(){this.refs.wrap&&(this.refs.wrap.style.paddingLeft=this.refs.wrap.style.paddingLeft="")},render:function(){var e=this.props,t=e.prefixCls,n=this.getWrapStyle();return e.visible&&(n.display=null),u["default"].createElement("div",null,this.getMaskElement(),u["default"].createElement("div",x({tabIndex:-1,onKeyDown:this.onKeyDown,className:t+"-wrap "+(e.wrapClassName||""),ref:"wrap",onClick:this.onMaskClick,role:"dialog","aria-labelledby":e.title?this.titleId:null,style:n},e.wrapProps),this.getDialogElement()))}});t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(10),s=i(a),l=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},u=o["default"].createClass({displayName:"LazyRenderBox",shouldComponentUpdate:function(e){return!!e.hiddenClassName||!!e.visible},render:function(){var e=this.props.className;this.props.hiddenClassName&&!this.props.visible&&(e+=" "+this.props.hiddenClassName);var t=(0,s["default"])({},this.props);return delete t.hiddenClassName,delete t.visible,t.className=e,o["default"].createElement("div",l({},t))}});t["default"]=u,e.exports=t["default"]},function(e,t){"use strict";var n={MAC_ENTER:3,BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,QUESTION_MARK:63,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,META:91,WIN_KEY_RIGHT:92,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUMLOCK:144,SEMICOLON:186,DASH:189,EQUALS:187,COMMA:188,PERIOD:190,SLASH:191,APOSTROPHE:192,SINGLE_QUOTE:222,OPEN_SQUARE_BRACKET:219,BACKSLASH:220,CLOSE_SQUARE_BRACKET:221,WIN_KEY:224,MAC_FF_META:224,WIN_IME:229};n.isTextModifyingKeyEvent=function(e){var t=e.keyCode;if(e.altKey&&!e.ctrlKey||e.metaKey||t>=n.F1&&t<=n.F12)return!1;switch(t){case n.ALT:case n.CAPS_LOCK:case n.CONTEXT_MENU:case n.CTRL:case n.DOWN:case n.END:case n.ESC:case n.HOME:case n.INSERT:case n.LEFT:case n.MAC_FF_META:case n.META:case n.NUMLOCK:case n.NUM_CENTER:case n.PAGE_DOWN:case n.PAGE_UP:case n.PAUSE:case n.PRINT_SCREEN:case n.RIGHT:case n.SHIFT:case n.UP:case n.WIN_KEY:case n.WIN_KEY_RIGHT:return!1;default:return!0}},n.isCharacterKey=function(e){if(e>=n.ZERO&&e<=n.NINE)return!0;if(e>=n.NUM_ZERO&&e<=n.NUM_MULTIPLY)return!0;if(e>=n.A&&e<=n.Z)return!0;if(window.navigation.userAgent.indexOf("WebKit")!==-1&&0===e)return!0;switch(e){case n.SPACE:case n.QUESTION_MARK:case n.NUM_PLUS:case n.NUM_MINUS:case n.NUM_PERIOD:case n.NUM_DIVISION:case n.SEMICOLON:case n.DASH:case n.EQUALS:case n.COMMA:case n.PERIOD:case n.SLASH:case n.APOSTROPHE:case n.SINGLE_QUOTE:case n.OPEN_SQUARE_BRACKET:case n.BACKSLASH:case n.CLOSE_SQUARE_BRACKET:return!0;default:return!1}},e.exports=n},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){var e=document.createElement("div");return document.body.appendChild(e),e}function o(e){function t(e,t,n){(!c||e._component||c(e))&&(e._container||(e._container=p(e)),l["default"].unstable_renderSubtreeIntoContainer(e,d(e,t),e._container,function(){e._component=this,n&&n.call(this)}))}function n(e){if(e._container){var t=e._container;l["default"].unmountComponentAtNode(t),t.parentNode.removeChild(t),e._container=null}}var i=e.autoMount,o=void 0===i||i,s=e.autoDestroy,u=void 0===s||s,c=e.isVisible,d=e.getComponent,f=e.getContainer,p=void 0===f?r:f,h=void 0;return o&&(h=a({},h,{componentDidMount:function(){t(this)},componentDidUpdate:function(){t(this)}})),o&&u||(h=a({},h,{renderComponent:function(e,n){t(this,e,n)}})),h=u?a({},h,{componentWillUnmount:function(){n(this)}}):a({},h,{removeContainer:function(){n(this)}})}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e};t["default"]=o;var s=n(9),l=i(s);e.exports=t["default"]},function(e,t){"use strict";function n(e){if(e||void 0===i){var t=document.createElement("div");t.style.width="100%",t.style.height="200px";var n=document.createElement("div"),r=n.style;r.position="absolute",r.top=0,r.left=0,r.pointerEvents="none",r.visibility="hidden",r.width="200px",r.height="150px",r.overflow="hidden",n.appendChild(t),document.body.appendChild(n);var o=t.offsetWidth;n.style.overflow="scroll";var a=t.offsetWidth;o===a&&(a=n.clientWidth),document.body.removeChild(n),i=o-a}return i}var i=void 0;e.exports=n},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){for(var t=e,n=0,i=0;t&&!isNaN(t.offsetLeft)&&!isNaN(t.offsetTop);)n+=t.offsetLeft-t.scrollLeft,i+=t.offsetTop-t.scrollTop,t=t.offsetParent;return{top:i,left:n}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=i(o),s=n(7),l=i(s),u=n(34),c=i(u),d=n(2),f=i(d),p=n(4),h=i(p),m=n(3),y=i(m),v=n(1),g=i(v),b=n(9),M=i(b),T=n(5),x=i(T),C=20,_=function(e){function t(n){(0,f["default"])(this,t);var i=(0,h["default"])(this,e.call(this,n));return i.onOverlayClicked=function(){i.props.open&&i.props.onOpenChange(!1,{overlayClicked:!0})},i.onTouchStart=function(e){if(!i.isTouching()){var t=e.targetTouches[0];i.setState({touchIdentifier:i.notTouch?null:t.identifier,touchStartX:t.clientX,touchStartY:t.clientY,touchCurrentX:t.clientX,touchCurrentY:t.clientY})}},i.onTouchMove=function(e){if(i.isTouching())for(var t=0;t<e.targetTouches.length;t++)if(e.targetTouches[t].identifier===i.state.touchIdentifier){i.setState({touchCurrentX:e.targetTouches[t].clientX,touchCurrentY:e.targetTouches[t].clientY});break}},i.onTouchEnd=function(){if(i.notTouch=!1,i.isTouching()){var e=i.touchSidebarWidth();(i.props.open&&e<i.state.sidebarWidth-i.props.dragToggleDistance||!i.props.open&&e>i.props.dragToggleDistance)&&i.props.onOpenChange(!i.props.open);var t=i.touchSidebarHeight();(i.props.open&&t<i.state.sidebarHeight-i.props.dragToggleDistance||!i.props.open&&t>i.props.dragToggleDistance)&&i.props.onOpenChange(!i.props.open), i.setState({touchIdentifier:null,touchStartX:null,touchStartY:null,touchCurrentX:null,touchCurrentY:null})}},i.onScroll=function(){i.isTouching()&&i.inCancelDistanceOnScroll()&&i.setState({touchIdentifier:null,touchStartX:null,touchStartY:null,touchCurrentX:null,touchCurrentY:null})},i.inCancelDistanceOnScroll=function(){var e=void 0;switch(i.props.position){case"right":e=Math.abs(i.state.touchCurrentX-i.state.touchStartX)<C;break;case"bottom":e=Math.abs(i.state.touchCurrentY-i.state.touchStartY)<C;break;case"top":e=Math.abs(i.state.touchStartY-i.state.touchCurrentY)<C;break;case"left":default:e=Math.abs(i.state.touchStartX-i.state.touchCurrentX)<C}return e},i.isTouching=function(){return null!==i.state.touchIdentifier},i.saveSidebarSize=function(){var e=M["default"].findDOMNode(i.refs.sidebar),t=e.offsetWidth,n=e.offsetHeight,o=r(M["default"].findDOMNode(i.refs.sidebar)).top,a=r(M["default"].findDOMNode(i.refs.dragHandle)).top;t!==i.state.sidebarWidth&&i.setState({sidebarWidth:t}),n!==i.state.sidebarHeight&&i.setState({sidebarHeight:n}),o!==i.state.sidebarTop&&i.setState({sidebarTop:o}),a!==i.state.dragHandleTop&&i.setState({dragHandleTop:a})},i.touchSidebarWidth=function(){return"right"===i.props.position?i.props.open&&window.innerWidth-i.state.touchStartX<i.state.sidebarWidth?i.state.touchCurrentX>i.state.touchStartX?i.state.sidebarWidth+i.state.touchStartX-i.state.touchCurrentX:i.state.sidebarWidth:Math.min(window.innerWidth-i.state.touchCurrentX,i.state.sidebarWidth):"left"===i.props.position?i.props.open&&i.state.touchStartX<i.state.sidebarWidth?i.state.touchCurrentX>i.state.touchStartX?i.state.sidebarWidth:i.state.sidebarWidth-i.state.touchStartX+i.state.touchCurrentX:Math.min(i.state.touchCurrentX,i.state.sidebarWidth):void 0},i.touchSidebarHeight=function(){if("bottom"===i.props.position)return i.props.open&&window.innerHeight-i.state.touchStartY<i.state.sidebarHeight?i.state.touchCurrentY>i.state.touchStartY?i.state.sidebarHeight+i.state.touchStartY-i.state.touchCurrentY:i.state.sidebarHeight:Math.min(window.innerHeight-i.state.touchCurrentY,i.state.sidebarHeight);if("top"===i.props.position){var e=i.state.touchStartY-i.state.sidebarTop;return i.props.open&&e<i.state.sidebarHeight?i.state.touchCurrentY>i.state.touchStartY?i.state.sidebarHeight:i.state.sidebarHeight-i.state.touchStartY+i.state.touchCurrentY:Math.min(i.state.touchCurrentY-i.state.dragHandleTop,i.state.sidebarHeight)}},i.renderStyle=function(e){var t=e.sidebarStyle,n=e.isTouching,r=e.overlayStyle,o=e.contentStyle;if("right"===i.props.position||"left"===i.props.position){if(t.transform="translateX(0%)",t.WebkitTransform="translateX(0%)",n){var a=i.touchSidebarWidth()/i.state.sidebarWidth;"right"===i.props.position&&(t.transform="translateX("+100*(1-a)+"%)",t.WebkitTransform="translateX("+100*(1-a)+"%)"),"left"===i.props.position&&(t.transform="translateX(-"+100*(1-a)+"%)",t.WebkitTransform="translateX(-"+100*(1-a)+"%)"),r.opacity=a,r.visibility="visible"}o&&(o[i.props.position]=i.state.sidebarWidth+"px")}if("top"===i.props.position||"bottom"===i.props.position){if(t.transform="translateY(0%)",t.WebkitTransform="translateY(0%)",n){var s=i.touchSidebarHeight()/i.state.sidebarHeight;"bottom"===i.props.position&&(t.transform="translateY("+100*(1-s)+"%)",t.WebkitTransform="translateY("+100*(1-s)+"%)"),"top"===i.props.position&&(t.transform="translateY(-"+100*(1-s)+"%)",t.WebkitTransform="translateY(-"+100*(1-s)+"%)"),r.opacity=s,r.visibility="visible"}o&&(o[i.props.position]=i.state.sidebarHeight+"px")}},i.state={sidebarWidth:0,sidebarHeight:0,sidebarTop:0,dragHandleTop:0,touchIdentifier:null,touchStartX:null,touchStartY:null,touchCurrentX:null,touchCurrentY:null,touchSupported:"object"===("undefined"==typeof window?"undefined":(0,c["default"])(window))&&"ontouchstart"in window},i}return(0,y["default"])(t,e),t.prototype.componentDidMount=function(){this.saveSidebarSize()},t.prototype.componentDidUpdate=function(){this.isTouching()||this.saveSidebarSize()},t.prototype.render=function(){var e,t=this,n=this.props,i=n.className,r=n.style,o=n.prefixCls,s=n.position,u=n.transitions,c=n.touch,d=n.enableDragHandle,f=n.sidebar,p=n.children,h=n.docked,m=n.open,y=(0,l["default"])({},this.props.sidebarStyle),v=(0,l["default"])({},this.props.contentStyle),b=(0,l["default"])({},this.props.overlayStyle),M=(e={},(0,a["default"])(e,i,!!i),(0,a["default"])(e,o,!0),(0,a["default"])(e,o+"-"+s,!0),e),T={style:r},C=this.isTouching();C?this.renderStyle({sidebarStyle:y,isTouching:!0,overlayStyle:b}):h?0!==this.state.sidebarWidth&&(M[o+"-docked"]=!0,this.renderStyle({sidebarStyle:y,contentStyle:v})):m&&(M[o+"-open"]=!0,this.renderStyle({sidebarStyle:y}),b.opacity=1,b.visibility="visible"),!C&&u||(y.transition="none",y.WebkitTransition="none",v.transition="none",b.transition="none");var _=null;return this.state.touchSupported&&c&&(m?(T.onTouchStart=function(e){t.notTouch=!0,t.onTouchStart(e)},T.onTouchMove=this.onTouchMove,T.onTouchEnd=this.onTouchEnd,T.onTouchCancel=this.onTouchEnd,T.onScroll=this.onScroll):d&&(_=g["default"].createElement("div",{className:o+"-draghandle",style:this.props.dragHandleStyle,onTouchStart:this.onTouchStart,onTouchMove:this.onTouchMove,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchEnd,ref:"dragHandle"}))),g["default"].createElement("div",(0,l["default"])({className:(0,x["default"])(M)},T),g["default"].createElement("div",{className:o+"-sidebar",style:y,ref:"sidebar"},f),g["default"].createElement("div",{className:o+"-overlay",style:b,role:"presentation",tabIndex:"0",ref:"overlay",onClick:this.onOverlayClicked}),g["default"].createElement("div",{className:o+"-content",style:v,ref:"content"},_,p))},t}(g["default"].Component);_.propTypes={prefixCls:g["default"].PropTypes.string,className:g["default"].PropTypes.string,children:g["default"].PropTypes.node.isRequired,style:g["default"].PropTypes.object,sidebarStyle:g["default"].PropTypes.object,contentStyle:g["default"].PropTypes.object,overlayStyle:g["default"].PropTypes.object,dragHandleStyle:g["default"].PropTypes.object,sidebar:g["default"].PropTypes.node.isRequired,docked:g["default"].PropTypes.bool,open:g["default"].PropTypes.bool,transitions:g["default"].PropTypes.bool,touch:g["default"].PropTypes.bool,enableDragHandle:g["default"].PropTypes.bool,position:g["default"].PropTypes.oneOf(["left","right","top","bottom"]),dragToggleDistance:g["default"].PropTypes.number,onOpenChange:g["default"].PropTypes.func},_.defaultProps={prefixCls:"rc-drawer",sidebarStyle:{},contentStyle:{},overlayStyle:{},dragHandleStyle:{},docked:!1,open:!1,transitions:!0,touch:!0,enableDragHandle:!0,position:"left",dragToggleDistance:30,onOpenChange:function(){}},t["default"]=_,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(359),o=i(r);t["default"]=o["default"],e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(6),o=i(r),a=n(7),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(5),v=i(y),g=n(364),b=i(g),M=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t=(0,s["default"])({},this.props),n=t.prefixCls,i=(0,v["default"])((e={},(0,o["default"])(e,""+t.className,!0),(0,o["default"])(e,n+"-handler-active",!t.disabled&&t.touchFeedback),e));return["prefixCls","touchFeedback"].forEach(function(e){t.hasOwnProperty(e)&&delete t[e]}),m["default"].createElement("span",(0,s["default"])({},t,{className:i}),t.children)},t}(h.Component);M.defaultProps={prefixCls:"am-stepper"},t["default"]=(0,b["default"])(M,"InputHandler"),e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}function o(e){e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),s=i(a),l=n(7),u=i(l),c=n(1),d=i(c),f=n(5),p=i(f),h=n(363),m=i(h),y=n(361),v=i(y),g=d["default"].createClass({displayName:"InputNumber",propTypes:{focusOnUpDown:c.PropTypes.bool,onChange:c.PropTypes.func,onKeyDown:c.PropTypes.func,prefixCls:c.PropTypes.string,disabled:c.PropTypes.bool,onFocus:c.PropTypes.func,onBlur:c.PropTypes.func,readOnly:c.PropTypes.bool,max:c.PropTypes.number,min:c.PropTypes.number,step:c.PropTypes.oneOfType([c.PropTypes.number,c.PropTypes.string])},mixins:[m["default"]],getDefaultProps:function(){return{focusOnUpDown:!0,prefixCls:"rc-input-number"}},componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(){this.props.focusOnUpDown&&this.state.focused&&document.activeElement!==this.refs.input&&this.focus()},onKeyDown:function(e){var t;38===e.keyCode?this.up(e):40===e.keyCode&&this.down(e);for(var n=arguments.length,i=Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];(t=this.props).onKeyDown.apply(t,[e].concat(i))},getValueFromEvent:function(e){return e.target.value},focus:function(){this.refs.input.focus()},render:function(){var e,t=(0,u["default"])({},this.props),n=t.prefixCls,i=t.disabled,a=t.readOnly,l=(0,p["default"])((e={},(0,s["default"])(e,n,!0),(0,s["default"])(e,t.className,!!t.className),(0,s["default"])(e,n+"-disabled",i),(0,s["default"])(e,n+"-focused",this.state.focused),e)),c="",f="",h=this.state.value;if(isNaN(h))c=n+"-handler-up-disabled",f=n+"-handler-down-disabled";else{var m=Number(h);m>=t.max&&(c=n+"-handler-up-disabled"),m<=t.min&&(f=n+"-handler-down-disabled")}var y=!t.readOnly&&!t.disabled,g=void 0;return g=this.state.focused?this.state.inputValue:this.state.value,void 0===g&&(g=""),d["default"].createElement("div",{className:l,style:t.style},d["default"].createElement("div",{className:n+"-handler-wrap"},d["default"].createElement(v["default"],{ref:"up",disabled:!!c||i||a,prefixCls:n,unselectable:"unselectable",onTouchStart:y&&!c?this.up:r,onTouchEnd:this.stop,onMouseDown:y&&!c?this.up:r,onMouseUp:this.stop,onMouseLeave:this.stop,className:n+"-handler "+n+"-handler-up "+c},d["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-up-inner",onClick:o})),d["default"].createElement(v["default"],{ref:"down",disabled:!!f||i||a,prefixCls:n,unselectable:"unselectable",onTouchStart:y&&!f?this.down:r,onTouchEnd:this.stop,onMouseDown:y&&!f?this.down:r,onMouseUp:this.stop,onMouseLeave:this.stop,className:n+"-handler "+n+"-handler-down "+f},d["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-down-inner",onClick:o}))),d["default"].createElement("div",{className:n+"-input-wrap"},d["default"].createElement("input",{placeholder:t.placeholder,onClick:t.onClick,className:n+"-input",autoComplete:"off",onFocus:this.onFocus,onBlur:this.onBlur,onKeyDown:this.onKeyDown,onKeyUp:this.stop,autoFocus:t.autoFocus,readOnly:t.readOnly,disabled:t.disabled,max:t.max,min:t.min,name:t.name,onChange:this.onChange,ref:"input",value:g})))}});t["default"]=g,e.exports=t["default"]},function(e,t){"use strict";function n(){}Object.defineProperty(t,"__esModule",{value:!0});var i=50,r=600;t["default"]={getDefaultProps:function(){return{max:1/0,min:-(1/0),step:1,style:{},defaultValue:null,onChange:n,onKeyDown:n,onFocus:n,onBlur:n}},getInitialState:function(){var e=void 0,t=this.props;return e="value"in t?t.value:t.defaultValue,e=this.toPrecisionAsStep(e),{inputValue:e,value:e,focused:t.autoFocus}},componentWillReceiveProps:function(e){if("value"in e){var t=this.toPrecisionAsStep(e.value);this.setState({inputValue:t,value:t})}},componentWillUnmount:function(){this.stop()},onChange:function(e){this.setInputValue(this.getValueFromEvent(e).trim())},onFocus:function(){var e;this.setState({focused:!0}),(e=this.props).onFocus.apply(e,arguments)},onBlur:function(e){var t;this.setState({focused:!1});var n=this.getCurrentValidValue(this.getValueFromEvent(e).trim());this.setValue(n);for(var i=arguments.length,r=Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];(t=this.props).onBlur.apply(t,[e].concat(r))},getCurrentValidValue:function(e){var t=e,n=this.props;return""===t?t="":isNaN(t)?t=this.state.value:(t=Number(t),t<n.min&&(t=n.min),t>n.max&&(t=n.max)),this.toPrecisionAsStep(t)},setValue:function(e){"value"in this.props||this.setState({value:e,inputValue:e});var t=isNaN(e)||""===e?void 0:e;t!==this.state.value?this.props.onChange(t):this.setState({inputValue:this.state.value})},setInputValue:function(e){this.setState({inputValue:e})},getPrecision:function(){var e=this.props,t=e.step.toString();if(t.indexOf("e-")>=0)return parseInt(t.slice(t.indexOf("e-")+1),10);var n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n},getPrecisionFactor:function(){var e=this.getPrecision();return Math.pow(10,e)},toPrecisionAsStep:function(e){if(isNaN(e)||""===e)return e;var t=this.getPrecision();return Number(Number(e).toFixed(Math.abs(t)))},upStep:function(e){var t=this.props,n=t.step,i=t.min,r=this.getPrecisionFactor(),o=void 0;return o="number"==typeof e?(r*e+r*n)/r:i===-(1/0)?n:i,this.toPrecisionAsStep(o)},downStep:function(e){var t=this.props,n=t.step,i=t.min,r=this.getPrecisionFactor(),o=void 0;return o="number"==typeof e?(r*e-r*n)/r:i===-(1/0)?-n:i,this.toPrecisionAsStep(o)},step:function(e,t){t&&t.preventDefault();var n=this.props;if(!n.disabled){var i=this.getCurrentValidValue(this.state.inputValue);if(this.setState({value:i}),!isNaN(i)){var r=this[e+"Step"](i);r>n.max||r<n.min||(this.setValue(r),this.setState({focused:!0}))}}},stop:function(){this.autoStepTimer&&clearTimeout(this.autoStepTimer)},down:function(e,t){var n=this;e.persist&&e.persist(),this.stop(),this.step("down",e),this.autoStepTimer=setTimeout(function(){n.down(e,!0)},t?i:r)},up:function(e,t){var n=this;e.persist&&e.persist(),this.stop(),this.step("up",e),this.autoStepTimer=setTimeout(function(){n.up(e,!0)},t?i:r)}},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=arguments.length<=1||void 0===arguments[1]?"":arguments[1],n=l["default"].createClass({displayName:"TouchableFeedbackComponent",propTypes:{onTouchStart:s.PropTypes.func,onTouchEnd:s.PropTypes.func,onTouchCancel:s.PropTypes.func},statics:{myName:t||"TouchableFeedbackComponent"},getInitialState:function(){return{touchFeedback:!1}},onTouchStart:function(e){this.props.onTouchStart&&this.props.onTouchStart(e),this.setTouchFeedbackState(!0)},onTouchEnd:function(e){this.props.onTouchEnd&&this.props.onTouchEnd(e),this.setTouchFeedbackState(!1)},onTouchCancel:function(e){this.props.onTouchCancel&&this.props.onTouchCancel(e),this.setTouchFeedbackState(!1)},onMouseDown:function(e){this.props.onTouchStart&&this.props.onTouchStart(e),this.setTouchFeedbackState(!0)},onMouseUp:function(e){this.props.onTouchEnd&&this.props.onTouchEnd(e),this.setTouchFeedbackState(!1)},setTouchFeedbackState:function(e){this.setState({touchFeedback:e})},render:function(){var t=u?{onTouchStart:this.onTouchStart,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchCancel}:{onMouseDown:this.onMouseDown,onMouseUp:this.state.touchFeedback?this.onMouseUp:void 0,onMouseLeave:this.state.touchFeedback?this.onMouseUp:void 0};return l["default"].createElement(e,(0,a["default"])({},this.props,{touchFeedback:this.state.touchFeedback},t))}});return n}Object.defineProperty(t,"__esModule",{value:!0});var o=n(7),a=i(o);t["default"]=r;var s=n(1),l=i(s),u="undefined"!=typeof window&&"ontouchstart"in window;e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=i(o),s=n(5),l=i(s),u=a["default"].createClass({displayName:"Notice",propTypes:{duration:o.PropTypes.number,onClose:o.PropTypes.func,children:o.PropTypes.any},getDefaultProps:function(){return{onEnd:function(){},onClose:function(){},duration:1.5,style:{right:"50%"}}},componentDidMount:function(){var e=this;this.props.duration&&(this.closeTimer=setTimeout(function(){e.close()},1e3*this.props.duration))},componentWillUnmount:function(){this.clearCloseTimer()},clearCloseTimer:function(){this.closeTimer&&(clearTimeout(this.closeTimer),this.closeTimer=null)},close:function(){this.clearCloseTimer(),this.props.onClose()},render:function(){var e,t=this.props,n=t.prefixCls+"-notice",i=(e={},r(e,""+n,1),r(e,n+"-closable",t.closable),r(e,t.className,!!t.className),e);return a["default"].createElement("div",{className:(0,l["default"])(i),style:t.style},a["default"].createElement("div",{className:n+"-content"},t.children),t.closable?a["default"].createElement("a",{tabIndex:"0",onClick:this.close,className:n+"-close"},a["default"].createElement("span",{className:n+"-close-x"})):null)}});t["default"]=u,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(){return"rcNotification_"+M+"_"+b++}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},s=n(1),l=i(s),u=n(9),c=i(u),d=n(45),f=i(d),p=n(368),h=i(p),m=n(5),y=i(m),v=n(365),g=i(v),b=0,M=Date.now(),T=l["default"].createClass({displayName:"Notification",propTypes:{prefixCls:s.PropTypes.string,transitionName:s.PropTypes.string,animation:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.object]),style:s.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-notification",animation:"fade",style:{top:65,left:"50%"}}},getInitialState:function(){return{notices:[]}},getTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},add:function(e){var t=e.key=e.key||o();this.setState(function(n){var i=n.notices;if(!i.filter(function(e){return e.key===t}).length)return{notices:i.concat(e)}})},remove:function(e){this.setState(function(t){return{notices:t.notices.filter(function(t){return t.key!==e})}})},render:function(){var e,t=this,n=this.props,i=this.state.notices.map(function(e){var i=(0,h["default"])(t.remove.bind(t,e.key),e.onClose);return l["default"].createElement(g["default"],a({prefixCls:n.prefixCls},e,{onClose:i}),e.content)}),o=(e={},r(e,n.prefixCls,1),r(e,n.className,!!n.className),e);return l["default"].createElement("div",{className:(0,y["default"])(o),style:n.style},l["default"].createElement(f["default"],{transitionName:this.getTransitionName()},i))}});T.newInstance=function(e){var t=e||{},n=document.createElement("div");document.body.appendChild(n);var i=c["default"].render(l["default"].createElement(T,t),n);return{notice:function(e){i.add(e)},removeNotice:function(e){i.remove(e)},component:i,destroy:function(){c["default"].unmountComponentAtNode(n),document.body.removeChild(n)}}},t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(366),o=i(r);t["default"]=o["default"],e.exports=t["default"]},function(e,t){"use strict";function n(){var e=arguments;return function(){for(var t=0;t<e.length;t++)e[t]&&e[t].apply&&e[t].apply(this,arguments)}}e.exports=n},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(2),o=i(r),a=n(4),s=i(a),l=n(3),u=i(l),c=n(1),d=i(c),f=n(113),p=i(f),h=function(e){function t(n){(0,o["default"])(this,t);var i=(0,s["default"])(this,e.call(this,n));return i.state={isTooltipVisible:!1},i}return(0,u["default"])(t,e),t.prototype.showTooltip=function(){this.setState({isTooltipVisible:!0})},t.prototype.hideTooltip=function(){this.setState({isTooltipVisible:!1})},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.className,i=e.tipTransitionName,r=e.tipFormatter,o=e.vertical,a=e.offset,s=e.value,l=e.dragging,u=e.noTip,c=o?{bottom:a+"%"}:{left:a+"%"},f=d["default"].createElement("div",{className:n,style:c,onMouseUp:this.showTooltip.bind(this),onMouseEnter:this.showTooltip.bind(this),onMouseLeave:this.hideTooltip.bind(this)});if(u)return f;var h=l||this.state.isTooltipVisible;return d["default"].createElement(p["default"],{prefixCls:t.replace("slider","tooltip"),placement:"top",visible:h,overlay:d["default"].createElement("span",null,r(s)),delay:0,transitionName:i},f)},t}(d["default"].Component);t["default"]=h,h.propTypes={prefixCls:d["default"].PropTypes.string,className:d["default"].PropTypes.string,vertical:d["default"].PropTypes.bool,offset:d["default"].PropTypes.number,tipTransitionName:d["default"].PropTypes.string,tipFormatter:d["default"].PropTypes.func,value:d["default"].PropTypes.number,dragging:d["default"].PropTypes.bool,noTip:d["default"].PropTypes.bool},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(34),s=i(a),l=n(6),u=i(l),c=n(1),d=i(c),f=n(5),p=i(f),h=function(e){var t=e.className,n=e.vertical,i=e.marks,r=e.included,a=e.upperBound,l=e.lowerBound,c=e.max,f=e.min,h=Object.keys(i),m=h.length,y=100/(m-1),v=.9*y,g=c-f,b=h.map(parseFloat).sort(function(e,t){return e-t}).map(function(e){var c,h=!r&&e===a||r&&e<=a&&e>=l,m=(0,p["default"])((c={},(0,u["default"])(c,t+"-text",!0),(0,u["default"])(c,t+"-text-active",h),c)),y={marginBottom:"-200%",bottom:(e-f)/g*100+"%"},b={width:v+"%",marginLeft:-v/2+"%",left:(e-f)/g*100+"%"},M=n?y:b,T=i[e],x="object"===("undefined"==typeof T?"undefined":(0,s["default"])(T))&&!d["default"].isValidElement(T),C=x?T.label:T,_=x?(0,o["default"])({},M,T.style):M;return d["default"].createElement("span",{className:m,style:_,key:e},C)});return d["default"].createElement("div",{className:t},b)};t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}function o(e){return e.touches.length>1||"touchend"===e.type.toLowerCase()&&e.touches.length>0}function a(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function s(e,t){return e?t.clientY:t.pageX}function l(e){e.stopPropagation(),e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var u=n(6),c=i(u),d=n(53),f=i(d),p=n(7),h=i(p),m=n(2),y=i(m),v=n(4),g=i(v),b=n(3),M=i(b),T=n(1),x=i(T),C=n(375),_=i(C),w=n(5),S=i(w),N=n(373),E=i(N),P=n(369),D=i(P),I=n(372),L=i(I),j=n(370),k=i(j),O=function(e){function t(n){(0,y["default"])(this,t);var i=(0,g["default"])(this,e.call(this,n)),r=n.range,o=n.min,a=n.max,s=r?Array.apply(null,Array(r+1)).map(function(){return o}):o,l="defaultValue"in n?n.defaultValue:s,u=void 0!==n.value?n.value:l,c=(r?u:[o,u]).map(function(e){return i.trimAlignValue(e)}),d=void 0;return d=r&&c[0]===c[c.length-1]&&c[0]===a?0:c.length-1,i.state={handle:null,recent:d,bounds:c},i}return(0,M["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){var t=this;if("value"in e||"min"in e||"max"in e){var n=this.state.bounds;if(e.range){var i=e.value||n,r=i.map(function(n){return t.trimAlignValue(n,e)});if(r.every(function(e,t){return e===n[t]}))return;this.setState({bounds:r}),n.some(function(n){return t.isValueOutOfBounds(n,e)})&&this.props.onChange(r)}else{var o=void 0!==e.value?e.value:n[1],a=this.trimAlignValue(o,e);if(a===n[1]&&n[0]===e.min)return;this.setState({bounds:[e.min,a]}),this.isValueOutOfBounds(n[1],e)&&this.props.onChange(a)}}},t.prototype.onChange=function(e){var t=this.props,n=!("value"in t);n?this.setState(e):e.handle&&this.setState({handle:e.handle});var i=(0,h["default"])({},this.state,e),r=t.range?i.bounds:i.bounds[1];t.onChange(r)},t.prototype.onMouseMove=function(e){var t=s(this.props.vertical,e);this.onMove(e,t)},t.prototype.onTouchMove=function(e){if(o(e))return void this.end("touch");var t=a(this.props.vertical,e);this.onMove(e,t)},t.prototype.onMove=function(e,t){l(e);var n=this.props,i=this.state,r=t-this.startPosition;r=this.props.vertical?-r:r;var o=r/this.getSliderLength()*(n.max-n.min),a=this.trimAlignValue(this.startValue+o),s=i[i.handle];if(a!==s){var u=[].concat((0,f["default"])(i.bounds));u[i.handle]=a;var c=i.handle;if(n.pushable!==!1){var d=i.bounds[c];this.pushSurroundingHandles(u,c,d)}else n.allowCross&&(u.sort(function(e,t){return e-t}),c=u.indexOf(a));this.onChange({handle:c,bounds:u})}},t.prototype.onTouchStart=function(e){if(!o(e)){var t=a(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("touch"),l(e)}},t.prototype.onMouseDown=function(e){if(0===e.button){var t=s(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("mouse"),l(e)}},t.prototype.onStart=function(e){var t=this.props;t.onBeforeChange(this.getValue());var n=this.calcValueByPos(e);this.startValue=n,this.startPosition=e;var i=this.state,r=i.bounds,o=1;if(this.props.range){for(var a=0,s=1;s<r.length-1;++s)n>r[s]&&(a=s);Math.abs(r[a+1]-n)<Math.abs(r[a]-n)&&(a+=1),o=a;var l=r[a+1]===r[a];l&&(o=i.recent),l&&n!==r[a+1]&&(o=n<r[a+1]?a:a+1)}this.setState({handle:o,recent:o});var u=i.bounds[o];if(n!==u){var c=[].concat((0,f["default"])(i.bounds));c[o]=n,this.onChange({bounds:c})}},t.prototype.getValue=function(){var e=this.state.bounds;return this.props.range?e:e[1]},t.prototype.getSliderLength=function(){var e=this.refs.slider;return e?this.props.vertical?e.clientHeight:e.clientWidth:0},t.prototype.getSliderStart=function(){var e=this.refs.slider,t=e.getBoundingClientRect();return this.props.vertical?t.top:t.left},t.prototype.getPrecision=function(e){var t=e.toString(),n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n},t.prototype.getPoints=function(){var e=this.props,t=e.marks,n=e.step,i=e.min,r=e.max,o=this._getPointsCache;if(!o||o.marks!==t||o.step!==n){var a=(0,h["default"])({},t);if(null!==n)for(var s=i;s<=r;s+=n)a[s]=s;var l=Object.keys(a).map(parseFloat);l.sort(function(e,t){return e-t}),this._getPointsCache={marks:t,step:n,points:l}}return this._getPointsCache.points},t.prototype.isValueOutOfBounds=function(e,t){return e<t.min||e>t.max},t.prototype.trimAlignValue=function(e,t){var n=this.state||{},i=n.handle,r=n.bounds,o=(0,h["default"])({},this.props,t||{}),a=o.marks,s=o.step,l=o.min,u=o.max,c=o.allowCross,d=e;d<=l&&(d=l),d>=u&&(d=u),!c&&null!=i&&i>0&&d<=r[i-1]&&(d=r[i-1]),!c&&null!=i&&i<r.length-1&&d>=r[i+1]&&(d=r[i+1]);var f=Object.keys(a).map(parseFloat);if(null!==s){var p=Math.round((d-l)/s)*s+l;f.push(p)}var m=f.map(function(e){return Math.abs(d-e)}),y=f[m.indexOf(Math.min.apply(Math,m))];return null!==s?parseFloat(y.toFixed(this.getPrecision(s))):y},t.prototype.pushHandleOnePoint=function(e,t,n){var i=this.getPoints(),r=i.indexOf(e[t]),o=r+n;if(o>=i.length||o<0)return!1;var a=t+n,s=i[o],l=this.props.pushable,u=n*(e[a]-s);return!!this.pushHandle(e,a,n,l-u)&&(e[t]=s,!0)},t.prototype.pushHandle=function(e,t,n,i){for(var r=e[t],o=e[t];n*(o-r)<i;){if(!this.pushHandleOnePoint(e,t,n))return e[t]=r,!1;o=e[t]}return!0},t.prototype.pushSurroundingHandles=function(e,t,n){var i=this.props.pushable,r=e[t],o=0;if(e[t+1]-r<i?o=1:r-e[t-1]<i&&(o=-1),0!==o){var a=t+o,s=o*(e[a]-r);this.pushHandle(e,a,o,i-s)||(e[t]=n)}},t.prototype.calcOffset=function(e){var t=this.props,n=t.min,i=t.max,r=(e-n)/(i-n);return 100*r},t.prototype.calcValue=function(e){var t=this.props,n=t.vertical,i=t.min,r=t.max,o=Math.abs(e/this.getSliderLength()),a=n?(1-o)*(r-i)+i:o*(r-i)+i;return a},t.prototype.calcValueByPos=function(e){var t=e-this.getSliderStart(),n=this.trimAlignValue(this.calcValue(t));return n},t.prototype.addDocumentEvents=function(e){"touch"===e?(this.onTouchMoveListener=(0,_["default"])(document,"touchmove",this.onTouchMove.bind(this)),this.onTouchUpListener=(0,_["default"])(document,"touchend",this.end.bind(this,"touch"))):"mouse"===e&&(this.onMouseMoveListener=(0,_["default"])(document,"mousemove",this.onMouseMove.bind(this)),this.onMouseUpListener=(0,_["default"])(document,"mouseup",this.end.bind(this,"mouse")))},t.prototype.removeEvents=function(e){"touch"===e?(this.onTouchMoveListener.remove(),this.onTouchUpListener.remove()):"mouse"===e&&(this.onMouseMoveListener.remove(),this.onMouseUpListener.remove())},t.prototype.end=function(e){this.removeEvents(e),this.props.onAfterChange(this.getValue()),this.setState({handle:null})},t.prototype.render=function(){var e,t=this,n=this.state,i=n.handle,o=n.bounds,a=this.props,s=a.className,l=a.prefixCls,u=a.disabled,d=a.vertical,f=a.dots,p=a.included,m=a.range,y=a.step,v=a.marks,g=a.max,b=a.min,M=a.tipTransitionName,C=a.tipFormatter,_=a.children,w=this.props.handle,N=o.map(function(e){return t.calcOffset(e)}),P=l+"-handle",D=o.map(function(e,t){var n;return(0,S["default"])((n={},(0,c["default"])(n,P,!0),(0,c["default"])(n,P+"-"+(t+1),!0),(0,c["default"])(n,P+"-lower",0===t),(0,c["default"])(n,P+"-upper",t===o.length-1),n))}),I=null===y||null===C,j={prefixCls:l,noTip:I,tipTransitionName:M,tipFormatter:C,vertical:d},O=o.map(function(e,t){return(0,T.cloneElement)(w,(0,h["default"])({},j,{className:D[t],value:e,offset:N[t],dragging:i===t,key:t}))});m||O.shift();for(var A=p||m,z=[],R=1;R<o.length;++R){var W,Y=(0,S["default"])((W={},(0,c["default"])(W,l+"-track",!0),(0,c["default"])(W,l+"-track-"+R,!0),W));z.push(x["default"].createElement(E["default"],{className:Y,vertical:d,included:A,offset:N[R-1],length:N[R]-N[R-1],key:R}))}var H=(0,S["default"])((e={},(0,c["default"])(e,l,!0),(0,c["default"])(e,l+"-disabled",u),(0,c["default"])(e,s,!!s),(0,c["default"])(e,l+"-vertical",this.props.vertical),e));return x["default"].createElement("div",{ref:"slider",className:H,onTouchStart:u?r:this.onTouchStart.bind(this),onMouseDown:u?r:this.onMouseDown.bind(this)},z,x["default"].createElement(L["default"],{prefixCls:l,vertical:d,marks:v,dots:f,step:y,included:A,lowerBound:o[0],upperBound:o[o.length-1],max:g,min:b}),O,x["default"].createElement(k["default"],{className:l+"-mark",vertical:d,marks:v,included:A,lowerBound:o[0],upperBound:o[o.length-1],max:g,min:b}),_)},t}(x["default"].Component);O.propTypes={min:x["default"].PropTypes.number,max:x["default"].PropTypes.number,step:x["default"].PropTypes.number,defaultValue:x["default"].PropTypes.oneOfType([x["default"].PropTypes.number,x["default"].PropTypes.arrayOf(x["default"].PropTypes.number)]),value:x["default"].PropTypes.oneOfType([x["default"].PropTypes.number,x["default"].PropTypes.arrayOf(x["default"].PropTypes.number)]),marks:x["default"].PropTypes.object,included:x["default"].PropTypes.bool,className:x["default"].PropTypes.string,prefixCls:x["default"].PropTypes.string,disabled:x["default"].PropTypes.bool,children:x["default"].PropTypes.any,onBeforeChange:x["default"].PropTypes.func,onChange:x["default"].PropTypes.func,onAfterChange:x["default"].PropTypes.func,handle:x["default"].PropTypes.element,tipTransitionName:x["default"].PropTypes.string,tipFormatter:x["default"].PropTypes.func,dots:x["default"].PropTypes.bool,range:x["default"].PropTypes.oneOfType([x["default"].PropTypes.bool,x["default"].PropTypes.number]),vertical:x["default"].PropTypes.bool,allowCross:x["default"].PropTypes.bool,pushable:x["default"].PropTypes.oneOfType([x["default"].PropTypes.bool,x["default"].PropTypes.number])},O.defaultProps={prefixCls:"rc-slider",className:"",tipTransitionName:"",min:0,max:100,step:1,marks:{},handle:x["default"].createElement(D["default"],null),onBeforeChange:r,onChange:r,onAfterChange:r,tipFormatter:function(e){return e},included:!0,disabled:!1,dots:!1,range:!1,vertical:!1,allowCross:!0,pushable:!1},t["default"]=O,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n,i,r,o){(0,f["default"])(!n||i>0,"`Slider[step]` should be a positive number in order to make Slider[dots] work.");var a=Object.keys(t).map(parseFloat);if(n)for(var s=r;s<=o;s+=i)a.indexOf(s)>=0||a.push(s); return a}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=i(o),s=n(1),l=i(s),u=n(5),c=i(u),d=n(448),f=i(d),p=function(e){var t=e.prefixCls,n=e.vertical,i=e.marks,o=e.dots,s=e.step,u=e.included,d=e.lowerBound,f=e.upperBound,p=e.max,h=e.min,m=p-h,y=r(n,i,o,s,h,p).map(function(e){var i,r=Math.abs(e-h)/m*100+"%",o=n?{bottom:r}:{left:r},s=!u&&e===f||u&&e<=f&&e>=d,p=(0,c["default"])((i={},(0,a["default"])(i,t+"-dot",!0),(0,a["default"])(i,t+"-dot-active",s),i));return l["default"].createElement("span",{className:p,style:o,key:e})});return l["default"].createElement("div",{className:t+"-step"},y)};t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=function(e){var t=e.className,n=e.included,i=e.vertical,r=e.offset,a=e.length,s={visibility:n?"visible":"hidden"};return i?(s.bottom=r+"%",s.height=a+"%"):(s.left=r+"%",s.width=a+"%"),o["default"].createElement("div",{className:t,style:s})};t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(371)},344,function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){var n={};for(var i in e)t.indexOf(i)>=0||Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}function a(e){return"string"==typeof e}function s(e){var t,n,i=e.className,s=e.prefixCls,u=e.style,d=e.tailWidth,p=e.status,h=void 0===p?"wait":p,m=e.iconPrefix,y=e.icon,v=e.wrapperStyle,g=e.adjustMarginRight,b=e.stepLast,M=e.stepNumber,T=e.description,x=e.title,C=o(e,["className","prefixCls","style","tailWidth","status","iconPrefix","icon","wrapperStyle","adjustMarginRight","stepLast","stepNumber","description","title"]),_=(0,f["default"])((t={},r(t,s+"-icon",!0),r(t,m+"icon",!0),r(t,m+"icon-"+y,y&&a(y)),r(t,m+"icon-check",!y&&"finish"===h),r(t,m+"icon-cross",!y&&"error"===h),t)),w=void 0;w=y&&!a(y)?c["default"].createElement("span",{className:s+"-icon"},y):y||"finish"===h||"error"===h?c["default"].createElement("span",{className:_}):c["default"].createElement("span",{className:s+"-icon"},M);var S=(0,f["default"])((n={},r(n,s+"-item",!0),r(n,s+"-item-last",b),r(n,s+"-status-"+h,!0),r(n,s+"-custom",y),r(n,i,!!i),n));return c["default"].createElement("div",l({},C,{className:S,style:l({width:d,marginRight:g},u)}),b?"":c["default"].createElement("div",{className:s+"-tail"},c["default"].createElement("i",null)),c["default"].createElement("div",{className:s+"-step"},c["default"].createElement("div",{className:s+"-head",style:{background:v.background||v.backgroundColor}},c["default"].createElement("div",{className:s+"-head-inner"},w)),c["default"].createElement("div",{className:s+"-main"},c["default"].createElement("div",{className:s+"-title",style:{background:v.background||v.backgroundColor}},x),T?c["default"].createElement("div",{className:s+"-description"},T):"")))}var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},u=n(1),c=i(u),d=n(5),f=i(d);s.propTypes={className:u.PropTypes.string,prefixCls:u.PropTypes.string,style:u.PropTypes.object,wrapperStyle:u.PropTypes.object,tailWidth:u.PropTypes.oneOfType([u.PropTypes.number,u.PropTypes.string]),status:u.PropTypes.string,iconPrefix:u.PropTypes.string,icon:u.PropTypes.node,adjustMarginRight:u.PropTypes.oneOfType([u.PropTypes.number,u.PropTypes.string]),stepLast:u.PropTypes.bool,stepNumber:u.PropTypes.string,description:u.PropTypes.any,title:u.PropTypes.any},e.exports=s},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){for(var n=Object.getOwnPropertyNames(t),i=0;i<n.length;i++){var r=n[i],o=Object.getOwnPropertyDescriptor(t,r);o&&o.configurable&&void 0===e[r]&&Object.defineProperty(e,r,o)}return e}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var i in e)t.indexOf(i)>=0||Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):r(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},d=n(1),f=i(d),p=n(9),h=i(p),m=n(5),y=i(m),v=function(e){function t(n){s(this,t);var i=l(this,e.call(this,n));return i.culcLastStepOffsetWidth=function(){var e=h["default"].findDOMNode(i);e.children.length>0&&(i.culcTimeout=setTimeout(function(){var t=e.lastChild.offsetWidth+1;i.state.lastStepOffsetWidth!==t&&i.setState({lastStepOffsetWidth:t})}))},i.state={lastStepOffsetWidth:0},i}return u(t,e),t.prototype.componentDidMount=function(){this.culcLastStepOffsetWidth()},t.prototype.componentDidUpdate=function(){this.culcLastStepOffsetWidth()},t.prototype.componentWillUnmount=function(){this.culcTimeout&&clearTimeout(this.culcTimeout)},t.prototype.render=function(){var e,t=this,n=this.props,i=n.prefixCls,r=n.style,s=void 0===r?{}:r,l=n.className,u=n.children,d=n.direction,p=n.labelPlacement,h=n.iconPrefix,m=n.status,v=n.size,g=n.current,b=a(n,["prefixCls","style","className","children","direction","labelPlacement","iconPrefix","status","size","current"]),M=u.length-1,T=this.state.lastStepOffsetWidth>0,x=(0,y["default"])((e={},o(e,i,!0),o(e,i+"-"+v,v),o(e,i+"-"+d,!0),o(e,i+"-label-"+p,"horizontal"===d),o(e,i+"-hidden",!T),o(e,l,l),e));return f["default"].createElement("div",c({className:x,style:s},b),f["default"].Children.map(u,function(e,r){var o="vertical"!==d&&r!==M&&T?100/M+"%":null,a="vertical"===d||r===M?null:-(t.state.lastStepOffsetWidth/M+1),l={stepNumber:(r+1).toString(),stepLast:r===M,tailWidth:o,adjustMarginRight:a,prefixCls:i,iconPrefix:h,wrapperStyle:s};return"error"===m&&r===g-1&&(l.className=n.prefixCls+"-next-error"),e.props.status||(r===g?l.status=m:r<g?l.status="finish":l.status="wait"),f["default"].cloneElement(e,l)},this))},t}(f["default"].Component);t["default"]=v,v.propTypes={prefixCls:d.PropTypes.string,iconPrefix:d.PropTypes.string,direction:d.PropTypes.string,labelPlacement:d.PropTypes.string,children:d.PropTypes.any,status:d.PropTypes.string,size:d.PropTypes.string},v.defaultProps={prefixCls:"rc-steps",iconPrefix:"rc",direction:"horizontal",labelPlacement:"horizontal",current:0,status:"process",size:""},e.exports=t["default"]},function(e,t,n){"use strict";var i=n(377);i.Step=n(376),e.exports=i},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(14),s=i(a),l=n(2),u=i(l),c=n(4),d=i(c),f=n(3),p=i(f),h=n(1),m=i(h),y=n(71),v=i(y),g=n(340),b=i(g),M=n(381),T=i(M),x=function(e){function t(n){(0,u["default"])(this,t);var i=(0,d["default"])(this,e.call(this,n));return i.onPanStart=i.onPanStart.bind(i),i.onPan=i.onPan.bind(i),i.onPanEnd=i.onPanEnd.bind(i),i.onTap=i.onTap.bind(i),i.openedLeft=!1,i.openedRight=!1,i}return(0,p["default"])(t,e),t.prototype.componentDidMount=function(){var e=this.props,t=e.left,n=e.right,i=this.refs.content.offsetWidth;this.contentWidth=i,this.btnsLeftWidth=t?i/5*t.length:0,this.btnsRightWidth=n?i/5*n.length:0},t.prototype.onPanStart=function(e){this.props.disabled||(this.panStartX=e.deltaX)},t.prototype.onPan=function(e){if(!this.props.disabled){var t=e.deltaX-this.panStartX;this.openedRight?t-=this.btnsRightWidth:this.openedLeft&&(t+=this.btnsLeftWidth),t<0&&this.props.right?this._setStyle(Math.min(t,0)):t>0&&this.props.left&&this._setStyle(Math.max(t,0))}},t.prototype.onPanEnd=function(e){if(!this.props.disabled){var t=e.deltaX-this.panStartX,n=this.contentWidth,i=this.btnsLeftWidth,r=this.btnsRightWidth,o=.33*n,a=t>o||t>i/2,s=t<-o||t<-r/2;this.openedRight&&(s=t-o<-o),this.openedLeft&&(a=t+o>o),s&&t<0?this.open(-r,!1,!0):a&&t>0?this.open(i,!0,!1):this.close()}},t.prototype.onTap=function(e){(this.openedLeft||this.openedRight)&&(e.preventDefault(),this.close())},t.prototype.onBtnClick=function(e){var t=e.onPress;t&&t(),this.props.autoClose&&this.close()},t.prototype._getContentEasing=function(e,t){return e<0&&e<t?t-Math.pow(t-e,.85):e>0&&e>t?t+Math.pow(e-t,.85):e},t.prototype._setStyle=function(e){var t=this.props,n=t.left,i=t.right,r=e>0?this.btnsLeftWidth:-this.btnsRightWidth,o=this._getContentEasing(e,r);if(this.refs.content.style.left=o+"px",n.length){var a=Math.max(Math.min(e,Math.abs(r)),0);this.refs.left.style.width=a+"px"}if(i.length){var s=Math.max(Math.min(-e,Math.abs(r)),0);this.refs.right.style.width=s+"px"}},t.prototype.open=function(e,t,n){this.openedLeft||this.openedRight||this.props.onOpen(),this.openedLeft=t,this.openedRight=n,this._setStyle(e)},t.prototype.close=function(){(this.openedLeft||this.openedRight)&&this.props.onClose(),this.openedLeft=!1,this.openedRight=!1,this._setStyle(0)},t.prototype.renderButtons=function(e,t){var n=this,i=this.props.prefixCls;return e&&e.length?m["default"].createElement("div",{className:i+"-actions "+i+"-actions-"+t,ref:t},e.map(function(e,t){return m["default"].createElement("div",{key:t,className:i+"-btn",style:e.style,onClick:function(){return n.onBtnClick(e)}},m["default"].createElement("div",{className:i+"-text"},e.text||"Click"))})):null},t.prototype.render=function(){var e=(0,T["default"])(this.props,["prefixCls","left","right","children"]),t=(0,s["default"])(e,2),n=t[0],i=n.prefixCls,r=n.left,a=n.right,l=n.children,u=t[1],c=(0,b["default"])(u,["disabled","autoClose","onOpen","onClose"]),d="DIRECTION_HORIZONTAL";return r.length&&0===a.length&&(d="DIRECTION_RIGHT"),a.length&&0===r.length&&(d="DIRECTION_LEFT"),r.length||a.length?m["default"].createElement("div",(0,o["default"])({className:""+i},c),m["default"].createElement(v["default"],{direction:d,onPanStart:this.onPanStart,onPan:this.onPan,onPanEnd:this.onPanEnd,onTap:this.onTap},m["default"].createElement("div",{className:i+"-content",ref:"content"},l)),this.renderButtons(r,"left"),this.renderButtons(a,"right")):m["default"].createElement("div",(0,o["default"])({ref:"content"},c),l)},t}(m["default"].Component);x.propTypes={prefixCls:h.PropTypes.string,autoClose:h.PropTypes.bool,disabled:h.PropTypes.bool,left:h.PropTypes.arrayOf(h.PropTypes.object),right:h.PropTypes.arrayOf(h.PropTypes.object),onOpen:h.PropTypes.func,onClose:h.PropTypes.func,children:h.PropTypes.any},x.defaultProps={prefixCls:"rc-swipeout",autoClose:!1,disabled:!1,left:[],right:[],onOpen:function(){},onClose:function(){}},t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(379);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return i(r)["default"]}}),e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n={},i={};return(0,a["default"])(e).forEach(function(r){t.indexOf(r)!==-1?n[r]=e[r]:i[r]=e[r]}),[n,i]}Object.defineProperty(t,"__esModule",{value:!0});var o=n(221),a=i(o);t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},a=n(1),s=i(a),l=n(384),u=i(l),c=n(386),d=n(39),f=i(d),p=n(387),h=i(p),m=s["default"].createClass({displayName:"Table",propTypes:{data:a.PropTypes.array,expandIconAsCell:a.PropTypes.bool,defaultExpandAllRows:a.PropTypes.bool,expandedRowKeys:a.PropTypes.array,defaultExpandedRowKeys:a.PropTypes.array,useFixedHeader:a.PropTypes.bool,columns:a.PropTypes.array,prefixCls:a.PropTypes.string,bodyStyle:a.PropTypes.object,style:a.PropTypes.object,rowKey:a.PropTypes.oneOfType([a.PropTypes.string,a.PropTypes.func]),rowClassName:a.PropTypes.func,expandedRowClassName:a.PropTypes.func,childrenColumnName:a.PropTypes.string,onExpand:a.PropTypes.func,onExpandedRowsChange:a.PropTypes.func,indentSize:a.PropTypes.number,onRowClick:a.PropTypes.func,columnsPageRange:a.PropTypes.array,columnsPageSize:a.PropTypes.number,expandIconColumnIndex:a.PropTypes.number,showHeader:a.PropTypes.bool,title:a.PropTypes.func,footer:a.PropTypes.func,emptyText:a.PropTypes.func,scroll:a.PropTypes.object,rowRef:a.PropTypes.func,getBodyWrapper:a.PropTypes.func},getDefaultProps:function(){return{data:[],useFixedHeader:!1,expandIconAsCell:!1,columns:[],defaultExpandAllRows:!1,defaultExpandedRowKeys:[],rowKey:"key",rowClassName:function(){return""},expandedRowClassName:function(){return""},onExpand:function(){},onExpandedRowsChange:function(){},prefixCls:"rc-table",bodyStyle:{},style:{},childrenColumnName:"children",indentSize:15,columnsPageSize:5,expandIconColumnIndex:0,showHeader:!0,scroll:{},rowRef:function(){return null},getBodyWrapper:function(e){return e},emptyText:function(){return"No Data"}}},getInitialState:function(){var e=this.props,t=[],n=[].concat(r(e.data));if(e.defaultExpandAllRows)for(var i=0;i<n.length;i++){var o=n[i];t.push(this.getRowKey(o)),n=n.concat(o[e.childrenColumnName]||[])}else t=e.expandedRowKeys||e.defaultExpandedRowKeys;return{expandedRowKeys:t,data:e.data,currentColumnsPage:0,currentHoverKey:null,scrollPosition:"left",fixedColumnsHeadRowsHeight:[],fixedColumnsBodyRowsHeight:[]}},componentDidMount:function(){this.resetScrollY();var e=this.isAnyColumnsFixed();e&&(this.syncFixedTableRowHeight(),this.resizeEvent=(0,h["default"])(window,"resize",(0,c.debounce)(this.syncFixedTableRowHeight,150)))},componentWillReceiveProps:function(e){"data"in e&&(this.setState({data:e.data}),e.data&&0!==e.data.length||this.resetScrollY()),"expandedRowKeys"in e&&this.setState({expandedRowKeys:e.expandedRowKeys}),e.columns!==this.props.columns&&(delete this.isAnyColumnsFixedCache,delete this.isAnyColumnsLeftFixedCache,delete this.isAnyColumnsRightFixedCache)},componentDidUpdate:function(){this.syncFixedTableRowHeight()},componentWillUnmount:function(){clearTimeout(this.timer),this.resizeEvent&&this.resizeEvent.remove()},onExpandedRowsChange:function(e){this.props.expandedRowKeys||this.setState({expandedRowKeys:e}),this.props.onExpandedRowsChange(e)},onExpanded:function(e,t,n){n&&(n.preventDefault(),n.stopPropagation());var i=this.findExpandedRow(t);if("undefined"==typeof i||e){if(!i&&e){var r=this.getExpandedRows().concat();r.push(this.getRowKey(t)),this.onExpandedRowsChange(r)}}else this.onRowDestroy(t);this.props.onExpand(e,t)},onRowDestroy:function(e){var t=this.getExpandedRows().concat(),n=this.getRowKey(e),i=-1;t.forEach(function(e,t){e===n&&(i=t)}),i!==-1&&t.splice(i,1),this.onExpandedRowsChange(t)},getRowKey:function(e,t){var n=this.props.rowKey;return"function"==typeof n?n(e,t):"undefined"!=typeof e[n]?e[n]:t},getExpandedRows:function(){return this.props.expandedRowKeys||this.state.expandedRowKeys},getHeader:function(e,t){var n=this.props,i=n.showHeader,r=n.expandIconAsCell,o=n.prefixCls,a=[];r&&"right"!==t&&a.push({key:"rc-table-expandIconAsCell",className:o+"-expand-icon-th",title:""}),a=a.concat(e||this.getCurrentColumns()).map(function(e){if(0!==e.colSpan)return s["default"].createElement("th",{key:e.key,colSpan:e.colSpan,className:e.className||""},e.title)});var l=this.state.fixedColumnsHeadRowsHeight,u=l[0]&&e?{height:l[0]}:null;return i?s["default"].createElement("thead",{className:o+"-thead"},s["default"].createElement("tr",{style:u},a)):null},getExpandedRow:function(e,t,n,i,r){var o=this.props.prefixCls;return s["default"].createElement("tr",{key:e+"-extra-row",style:{display:n?"":"none"},className:o+"-expanded-row "+i},this.props.expandIconAsCell&&"right"!==r?s["default"].createElement("td",{key:"rc-table-expand-icon-placeholder"}):null,s["default"].createElement("td",{colSpan:this.props.columns.length},"right"!==r?t:"&nbsp;"))},getRowsByData:function(e,t,n,i,r){for(var a=this.props,l=a.childrenColumnName,c=a.expandedRowRender,d=a.expandRowByClick,f=this.state.fixedColumnsBodyRowsHeight,p=[],h=a.rowClassName,m=a.rowRef,y=a.expandedRowClassName,v=a.data.some(function(e){return e[l]}),g=a.onRowClick,b=this.isAnyColumnsFixed(),M="right"!==r&&a.expandIconAsCell,T="right"!==r?a.expandIconColumnIndex:-1,x=0;x<e.length;x++){var C=e[x],_=this.getRowKey(C,x),w=C[l],S=this.isRowExpanded(C),N=void 0;c&&S&&(N=c(C,x,n));var E=h(C,x,n);this.state.currentHoverKey===_&&(E+=" "+a.prefixCls+"-row-hover");var P={};b&&(P.onHover=this.handleRowHover);var D=r&&f[x]?{height:f[x]}:{};p.push(s["default"].createElement(u["default"],o({indent:n,indentSize:a.indentSize,needIndentSpaced:v,className:E,record:C,expandIconAsCell:M,onDestroy:this.onRowDestroy,index:x,visible:t,expandRowByClick:d,onExpand:this.onExpanded,expandable:w||c,expanded:S,prefixCls:a.prefixCls+"-row",childrenColumnName:l,columns:i||this.getCurrentColumns(),expandIconColumnIndex:T,onRowClick:g,style:D},P,{key:_,hoverKey:_,ref:m(C,x,n)})));var I=t&&S;N&&S&&p.push(this.getExpandedRow(_,N,I,y(C,x,n),r)),w&&(p=p.concat(this.getRowsByData(w,I,n+1,i,r)))}return p},getRows:function(e,t){return this.getRowsByData(this.state.data,!0,0,e,t)},getColGroup:function(e,t){var n=[];return this.props.expandIconAsCell&&"right"!==t&&n.push(s["default"].createElement("col",{className:this.props.prefixCls+"-expand-icon-col",key:"rc-table-expand-icon-col"})),n=n.concat((e||this.props.columns).map(function(e){return s["default"].createElement("col",{key:e.key,style:{width:e.width,minWidth:e.width}})})),s["default"].createElement("colgroup",null,n)},getCurrentColumns:function(){var e=this,t=this.props,n=t.columns,i=t.columnsPageRange,r=t.columnsPageSize,a=t.prefixCls,s=this.state.currentColumnsPage;return!i||i[0]>i[1]?n:n.map(function(t,n){var l=o({},t);if(n>=i[0]&&n<=i[1]){var u=i[0]+s*r,c=i[0]+(s+1)*r-1;c>i[1]&&(c=i[1]),(n<u||n>c)&&(l.className=l.className||"",l.className+=" "+a+"-column-hidden"),l=e.wrapPageColumn(l,n===u,n===c)}return l})},getLeftFixedTable:function(){var e=this.props.columns,t=e.filter(function(e){return"left"===e.fixed||e.fixed===!0});return this.getTable({columns:t,fixed:"left"})},getRightFixedTable:function(){var e=this.props.columns,t=e.filter(function(e){return"right"===e.fixed});return this.getTable({columns:t,fixed:"right"})},getTable:function(){var e=this,t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=t.columns,i=t.fixed,r=this.props,a=r.prefixCls,l=r.scroll,u=void 0===l?{}:l,d=r.getBodyWrapper,f=this.props.useFixedHeader,p=o({},this.props.bodyStyle),h={},m="";if((u.x||n)&&(m=a+"-fixed",p.overflowX=p.overflowX||"auto"),u.y){i?p.height=p.height||u.y:p.maxHeight=p.maxHeight||u.y,p.overflowY=p.overflowY||"scroll",f=!0;var y=(0,c.measureScrollbar)();y>0&&((i?p:h).marginBottom="-"+y+"px",(i?p:h).paddingBottom="0px")}var v=function(){var t=arguments.length<=0||void 0===arguments[0]||arguments[0],r=arguments.length<=1||void 0===arguments[1]||arguments[1],o={};!n&&u.x&&(u.x===!0?o.tableLayout="fixed":o.width=u.x);var l=r?d(s["default"].createElement("tbody",{className:a+"-tbody"},e.getRows(n,i))):null;return s["default"].createElement("table",{className:m,style:o},e.getColGroup(n,i),t?e.getHeader(n,i):null,l)},g=void 0;f&&(g=s["default"].createElement("div",{className:a+"-header",ref:n?null:"headTable",style:h,onMouseOver:this.detectScrollTarget,onTouchStart:this.detectScrollTarget,onScroll:this.handleBodyScroll},v(!0,!1)));var b=s["default"].createElement("div",{className:a+"-body",style:p,ref:"bodyTable",onMouseOver:this.detectScrollTarget,onTouchStart:this.detectScrollTarget,onScroll:this.handleBodyScroll},v(!f));if(n&&n.length){var M=void 0;"left"===n[0].fixed||n[0].fixed===!0?M="fixedColumnsBodyLeft":"right"===n[0].fixed&&(M="fixedColumnsBodyRight"),delete p.overflowX,delete p.overflowY,b=s["default"].createElement("div",{className:a+"-body-outer",style:o({},p)},s["default"].createElement("div",{className:a+"-body-inner",ref:M,onMouseOver:this.detectScrollTarget,onTouchStart:this.detectScrollTarget,onScroll:this.handleBodyScroll},v(!f)))}return s["default"].createElement("span",null,g,b)},getTitle:function(){var e=this.props,t=e.title,n=e.prefixCls;return t?s["default"].createElement("div",{className:n+"-title"},t(this.state.data)):null},getFooter:function(){var e=this.props,t=e.footer,n=e.prefixCls;return t?s["default"].createElement("div",{className:n+"-footer"},t(this.state.data)):null},getEmptyText:function(){var e=this.props,t=e.emptyText,n=e.prefixCls,i=e.data;return i.length?null:s["default"].createElement("div",{className:n+"-placeholder"},t())},getMaxColumnsPage:function(){var e=this.props,t=e.columnsPageRange,n=e.columnsPageSize;return Math.ceil((t[1]-t[0]+1)/n)-1},goToColumnsPage:function(e){var t=this.getMaxColumnsPage(),n=e;n<0&&(n=0),n>t&&(n=t),this.setState({currentColumnsPage:n})},syncFixedTableRowHeight:function(){var e=this,t=this.props.prefixCls,n=this.refs.headTable?this.refs.headTable.querySelectorAll("tr"):[],i=this.refs.bodyTable.querySelectorAll("."+t+"-row")||[],r=[].map.call(n,function(e){return e.getBoundingClientRect().height||"auto"}),o=[].map.call(i,function(e){return e.getBoundingClientRect().height||"auto"});(0,f["default"])(this.state.fixedColumnsHeadRowsHeight,r)&&(0,f["default"])(this.state.fixedColumnsBodyRowsHeight,o)||(this.timer=setTimeout(function(){e.setState({fixedColumnsHeadRowsHeight:r,fixedColumnsBodyRowsHeight:o})}))},resetScrollY:function(){this.refs.headTable&&(this.refs.headTable.scrollLeft=0),this.refs.bodyTable&&(this.refs.bodyTable.scrollLeft=0)},prevColumnsPage:function(){this.goToColumnsPage(this.state.currentColumnsPage-1)},nextColumnsPage:function(){this.goToColumnsPage(this.state.currentColumnsPage+1)},wrapPageColumn:function(e,t,n){var i=this.props.prefixCls,r=this.state.currentColumnsPage,o=this.getMaxColumnsPage(),a=i+"-prev-columns-page";0===r&&(a+=" "+i+"-prev-columns-page-disabled");var l=s["default"].createElement("span",{className:a,onClick:this.prevColumnsPage}),u=i+"-next-columns-page";r===o&&(u+=" "+i+"-next-columns-page-disabled");var c=s["default"].createElement("span",{className:u,onClick:this.nextColumnsPage});return t&&(e.title=s["default"].createElement("span",null,l,e.title),e.className=(e.className||"")+" "+i+"-column-has-prev"),n&&(e.title=s["default"].createElement("span",null,e.title,c),e.className=(e.className||"")+" "+i+"-column-has-next"),e},findExpandedRow:function(e){var t=this,n=this.getExpandedRows().filter(function(n){return n===t.getRowKey(e)});return n[0]},isRowExpanded:function(e){return"undefined"!=typeof this.findExpandedRow(e)},detectScrollTarget:function(e){this.scrollTarget!==e.currentTarget&&(this.scrollTarget=e.currentTarget)},isAnyColumnsFixed:function(){return"isAnyColumnsFixedCache"in this?this.isAnyColumnsFixedCache:(this.isAnyColumnsFixedCache=this.getCurrentColumns().some(function(e){return!!e.fixed}),this.isAnyColumnsFixedCache)},isAnyColumnsLeftFixed:function(){return"isAnyColumnsLeftFixedCache"in this?this.isAnyColumnsLeftFixedCache:(this.isAnyColumnsLeftFixedCache=this.getCurrentColumns().some(function(e){return"left"===e.fixed||e.fixed===!0}),this.isAnyColumnsLeftFixedCache)},isAnyColumnsRightFixed:function(){return"isAnyColumnsRightFixedCache"in this?this.isAnyColumnsRightFixedCache:(this.isAnyColumnsRightFixedCache=this.getCurrentColumns().some(function(e){return"right"===e.fixed}),this.isAnyColumnsRightFixedCache)},handleBodyScroll:function(e){if(e.target===this.scrollTarget){var t=this.props.scroll,n=void 0===t?{}:t,i=this.refs,r=i.headTable,o=i.bodyTable,a=i.fixedColumnsBodyLeft,s=i.fixedColumnsBodyRight;n.x&&(e.target===o&&r?r.scrollLeft=e.target.scrollLeft:e.target===r&&o&&(o.scrollLeft=e.target.scrollLeft),0===e.target.scrollLeft?this.setState({scrollPosition:"left"}):e.target.scrollLeft+1>=e.target.children[0].getBoundingClientRect().width-e.target.getBoundingClientRect().width?this.setState({scrollPosition:"right"}):"middle"!==this.state.scrollPosition&&this.setState({scrollPosition:"middle"})),n.y&&(a&&e.target!==a&&(a.scrollTop=e.target.scrollTop),s&&e.target!==s&&(s.scrollTop=e.target.scrollTop),o&&e.target!==o&&(o.scrollTop=e.target.scrollTop))}},handleRowHover:function(e,t){this.setState({currentHoverKey:e?t:null})},render:function(){var e=this.props,t=e.prefixCls,n=e.prefixCls;e.className&&(n+=" "+e.className),e.columnsPageRange&&(n+=" "+t+"-columns-paging"),(e.useFixedHeader||e.scroll&&e.scroll.y)&&(n+=" "+t+"-fixed-header"),n+=" "+t+"-scroll-position-"+this.state.scrollPosition;var i=this.isAnyColumnsFixed()||e.scroll.x||e.scroll.y;return s["default"].createElement("div",{className:n,style:e.style},this.getTitle(),s["default"].createElement("div",{className:t+"-content"},this.isAnyColumnsLeftFixed()&&s["default"].createElement("div",{className:t+"-fixed-left"},this.getLeftFixedTable()),s["default"].createElement("div",{className:i?t+"-scroll":""},this.getTable(),this.getEmptyText(),this.getFooter()),this.isAnyColumnsRightFixed()&&s["default"].createElement("div",{className:t+"-fixed-right"},this.getRightFixedTable())))}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(339),s=i(a),l=n(39),u=i(l),c=n(109),d=i(c),f=o["default"].createClass({displayName:"TableCell",propTypes:{record:r.PropTypes.object,prefixCls:r.PropTypes.string,isColumnHaveExpandIcon:r.PropTypes.bool,index:r.PropTypes.number,expanded:r.PropTypes.bool,expandable:r.PropTypes.any,onExpand:r.PropTypes.func,needIndentSpaced:r.PropTypes.bool,indent:r.PropTypes.number,indentSize:r.PropTypes.number,column:r.PropTypes.object},shouldComponentUpdate:function(e){return!(0,u["default"])(e,this.props)},isInvalidRenderCellText:function(e){return e&&!o["default"].isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)},render:function p(){var e=this.props,t=e.record,n=e.indentSize,i=e.prefixCls,r=e.indent,a=e.isColumnHaveExpandIcon,l=e.index,u=e.expandable,c=e.onExpand,f=e.needIndentSpaced,h=e.expanded,m=e.column,y=m.dataIndex,p=m.render,v=m.className,g=s["default"].get(t,y),b=void 0,M=void 0,T=void 0;p&&(g=p(g,t,l),this.isInvalidRenderCellText(g)&&(b=g.props||{},T=b.rowSpan,M=b.colSpan,g=g.children)),this.isInvalidRenderCellText(g)&&(g=null);var x=o["default"].createElement(d["default"],{expandable:u,prefixCls:i,onExpand:c,needIndentSpaced:f,expanded:h,record:t}),C=o["default"].createElement("span",{style:{paddingLeft:n*r+"px"},className:i+"-indent indent-level-"+r});return 0===T||0===M?null:o["default"].createElement("td",{colSpan:M,rowSpan:T,className:v||""},a?C:null,a?x:null,g)}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},o=n(1),a=i(o),s=n(39),l=i(s),u=n(383),c=i(u),d=n(109),f=i(d),p=a["default"].createClass({displayName:"TableRow",propTypes:{onDestroy:o.PropTypes.func,onRowClick:o.PropTypes.func,record:o.PropTypes.object,prefixCls:o.PropTypes.string,expandIconColumnIndex:o.PropTypes.number,onHover:o.PropTypes.func,columns:o.PropTypes.array,style:o.PropTypes.object,visible:o.PropTypes.bool,index:o.PropTypes.number,hoverKey:o.PropTypes.any,expanded:o.PropTypes.bool,expandable:o.PropTypes.any,onExpand:o.PropTypes.func,needIndentSpaced:o.PropTypes.bool,className:o.PropTypes.string,indent:o.PropTypes.number,indentSize:o.PropTypes.number,expandIconAsCell:o.PropTypes.bool,expandRowByClick:o.PropTypes.bool},getDefaultProps:function(){return{onRowClick:function(){},onDestroy:function(){},expandIconColumnIndex:0,expandRowByClick:!1,onHover:function(){}}},shouldComponentUpdate:function(e){return!(0,l["default"])(e,this.props)},componentWillUnmount:function(){this.props.onDestroy(this.props.record)},onRowClick:function h(e){var t=this.props,n=t.record,i=t.index,h=t.onRowClick,r=t.expandable,o=t.expandRowByClick,a=t.expanded,s=t.onExpand;r&&o&&s(!a,n),h(n,i,e)},onMouseEnter:function(){var e=this.props,t=e.onHover,n=e.hoverKey;t(!0,n)},onMouseLeave:function(){var e=this.props,t=e.onHover,n=e.hoverKey;t(!1,n)},render:function(){for(var e=this.props,t=e.prefixCls,n=e.columns,i=e.record,o=e.style,s=e.visible,l=e.index,u=e.expandIconColumnIndex,d=e.expandIconAsCell,p=e.expanded,h=e.expandRowByClick,m=e.expandable,y=e.onExpand,v=e.needIndentSpaced,g=e.className,b=e.indent,M=e.indentSize,T=[],x=0;x<n.length;x++){d&&0===x&&T.push(a["default"].createElement("td",{className:t+"-expand-icon-cell",key:"rc-table-expand-icon-cell"},a["default"].createElement(f["default"],{expandable:m,prefixCls:t,onExpand:y,needIndentSpaced:v,expanded:p,record:i})));var C=!d&&!h&&x===u;T.push(a["default"].createElement(c["default"],{prefixCls:t,record:i,indentSize:M,indent:b,index:l,expandable:m,onExpand:y,needIndentSpaced:v,expanded:p,isColumnHaveExpandIcon:C,column:n[x],key:n[x].key}))}return a["default"].createElement("tr",{onClick:this.onRowClick,onMouseEnter:this.onMouseEnter,onMouseLeave:this.onMouseLeave,className:t+" "+g+" "+t+"-level-"+b,style:s?o:r({},o,{display:"none"})},T)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(382)},function(e,t){"use strict";function n(){if("undefined"==typeof document||"undefined"==typeof window)return 0;if(r)return r;var e=document.createElement("div");for(var t in o)o.hasOwnProperty(t)&&(e.style[t]=o[t]);document.body.appendChild(e);var n=e.offsetWidth-e.clientWidth;return document.body.removeChild(e),r=n}function i(e,t,n){var i=void 0;return function(){var r=this,o=arguments;o[0]&&o[0].persist&&o[0].persist();var a=function(){i=null,n||e.apply(r,o)},s=n&&!i;clearTimeout(i),i=setTimeout(a,t),s&&e.apply(r,o)}}Object.defineProperty(t,"__esModule",{value:!0}),t.measureScrollbar=n,t.debounce=i;var r=void 0,o={position:"absolute",top:"-9999px",width:"50px",height:"50px",overflow:"scroll"}},344,function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(389),s=i(a),l=n(110),u=i(l),c=o["default"].createClass({displayName:"InkTabBar",mixins:[u["default"],s["default"]],render:function(){var e=this.getInkBarNode(),t=this.getTabs();return this.getRootNode([e,t])}});t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],i="scroll"+(t?"Top":"Left");if("number"!=typeof n){var r=e.document;n=r.documentElement[i],"number"!=typeof n&&(n=r.body[i])}return n}function o(e){var t=void 0,n=void 0,i=void 0,o=e.ownerDocument,a=o.body,s=o&&o.documentElement;t=e.getBoundingClientRect(),n=t.left,i=t.top,n-=s.clientLeft||a.clientLeft||0,i-=s.clientTop||a.clientTop||0;var l=o.defaultView||o.parentWindow;return n+=r(l),i+=r(l,!0),{left:n,top:i}}function a(e,t){var n=e.refs,i=n.nav||n.root,r=o(i),a=n.inkBar,s=n.activeTab,l=a.style,c=e.props.tabBarPosition;if(t&&(l.display="none"),s){var d=s,f=o(d),p=(0,u.isTransformSupported)(l);if("top"===c||"bottom"===c){ var h=f.left-r.left;p?((0,u.setTransform)(l,"translate3d("+h+"px,0,0)"),l.width=d.offsetWidth+"px",l.height=""):(l.left=h+"px",l.top="",l.bottom="",l.right=i.offsetWidth-h-d.offsetWidth+"px")}else{var m=f.top-r.top;p?((0,u.setTransform)(l,"translate3d(0,"+m+"px,0)"),l.height=d.offsetHeight+"px",l.width=""):(l.left="",l.right="",l.top=m+"px",l.bottom=i.offsetHeight-m-d.offsetHeight+"px")}}l.display=s?"block":"none"}Object.defineProperty(t,"__esModule",{value:!0});var s=n(6),l=i(s);t.getScroll=r;var u=n(70),c=n(1),d=i(c),f=n(5),p=i(f);t["default"]={getDefaultProps:function(){return{inkBarAnimated:!0}},componentDidUpdate:function(){a(this)},componentDidMount:function(){a(this,!0)},getInkBarNode:function(){var e,t=this.props,n=t.prefixCls,i=t.styles,r=t.inkBarAnimated,o=n+"-ink-bar",a=(0,p["default"])((e={},(0,l["default"])(e,o,!0),(0,l["default"])(e,r?o+"-animated":o+"-no-animated",!0),e));return d["default"].createElement("div",{style:i.inkBar,className:a,key:"inkBar",ref:"inkBar"})}}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={LEFT:37,UP:38,RIGHT:39,DOWN:40},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.maxIndex,n=e.startIndex,i=e.delta,r=e.viewSize,o=n+-i/r;return o<0?o=Math.exp(o*v)-1:o>t&&(o=t+1-Math.exp((t-o)*v)),o}function o(e){var t=(0,y.isVertical)(this.props.tabBarPosition)?e.deltaY:e.deltaX,n=r({maxIndex:this.maxIndex,viewSize:this.viewSize,startIndex:this.startIndex,delta:t}),i=t<0?Math.floor(n+1):Math.floor(n);if(i<0?i=0:i>this.maxIndex&&(i=this.maxIndex),!this.children[i].props.disabled)return n}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),s=i(a),l=n(69),u=i(l),c=n(1),d=i(c),f=n(71),p=i(f),h=n(9),m=i(h),y=n(70),v=.6,g=d["default"].createClass({displayName:"SwipeableTabContent",propTypes:{tabBarPosition:c.PropTypes.string,onChange:c.PropTypes.func,children:c.PropTypes.any,hammerOptions:c.PropTypes.any,animated:c.PropTypes.bool,activeKey:c.PropTypes.string},getDefaultProps:function(){return{animated:!0}},componentDidMount:function(){this.rootNode=m["default"].findDOMNode(this)},onPanStart:function(){var e=this.props,t=e.tabBarPosition,n=e.children,i=e.activeKey,r=e.animated,o=this.startIndex=(0,y.getActiveIndex)(n,i);o!==-1&&(r&&(0,y.setTransition)(this.rootNode.style,"none"),this.startDrag=!0,this.children=(0,y.toArray)(n),this.maxIndex=this.children.length-1,this.viewSize=(0,y.isVertical)(t)?this.rootNode.offsetHeight:this.rootNode.offsetWidth)},onPan:function(e){if(this.startDrag){var t=this.props.tabBarPosition,n=o.call(this,e);void 0!==n&&(0,y.setTransform)(this.rootNode.style,(0,y.getTransformByIndex)(n,t))}},onPanEnd:function(e){this.startDrag&&this.end(e)},onSwipe:function(e){this.end(e,!0)},end:function(e,t){var n=this.props,i=n.tabBarPosition,r=n.animated;this.startDrag=!1,r&&(0,y.setTransition)(this.rootNode.style,"");var a=o.call(this,e),s=this.startIndex;if(void 0!==a)if(a<0)s=0;else if(a>this.maxIndex)s=this.maxIndex;else if(t){var l=(0,y.isVertical)(i)?e.deltaY:e.deltaX;s=l<0?Math.ceil(a):Math.floor(a)}else{var u=Math.floor(a);s=a-u>.6?u+1:u}this.children[s].props.disabled||(this.startIndex===s?r&&(0,y.setTransform)(this.rootNode.style,(0,y.getTransformByIndex)(s,this.props.tabBarPosition)):this.props.onChange((0,y.getActiveKey)(this.props.children,s)))},render:function(){var e=this.props,t=e.tabBarPosition,n=e.hammerOptions,i=e.animated,r={};(0,y.isVertical)(t)&&(r={vertical:!0});var o={onSwipe:this.onSwipe,onPanStart:this.onPanStart};return i!==!1&&(o=(0,s["default"])({},o,{onPan:this.onPan,onPanEnd:this.onPanEnd})),d["default"].createElement(p["default"],(0,s["default"])({},o,r,{options:n}),d["default"].createElement(u["default"],this.props))}});t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(110),s=i(a),l=o["default"].createClass({displayName:"TabBar",mixins:[s["default"]],render:function(){var e=this.getTabs();return this.getRootNode(e)}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}function o(e){var t=void 0;return u["default"].Children.forEach(e.children,function(e){!e||t||e.props.disabled||(t=e.key)}),t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),s=i(a),l=n(1),u=i(l),c=n(390),d=i(c),f=n(111),p=i(f),h=n(5),m=i(h),y=u["default"].createClass({displayName:"Tabs",propTypes:{destroyInactiveTabPane:l.PropTypes.bool,renderTabBar:l.PropTypes.func.isRequired,renderTabContent:l.PropTypes.func.isRequired,onChange:l.PropTypes.func,children:l.PropTypes.any,prefixCls:l.PropTypes.string,className:l.PropTypes.string,tabBarPosition:l.PropTypes.string,style:l.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-tabs",destroyInactiveTabPane:!1,onChange:r,tabBarPosition:"top",style:{}}},getInitialState:function(){var e=this.props,t=void 0;return t="activeKey"in e?e.activeKey:"defaultActiveKey"in e?e.defaultActiveKey:o(e),{activeKey:t}},componentWillReceiveProps:function(e){"activeKey"in e&&this.setState({activeKey:e.activeKey})},onTabClick:function(e){this.tabBar.props.onTabClick&&this.tabBar.props.onTabClick(e),this.setActiveKey(e)},onNavKeyDown:function(e){var t=e.keyCode;if(t===d["default"].RIGHT||t===d["default"].DOWN){e.preventDefault();var n=this.getNextActiveKey(!0);this.onTabClick(n)}else if(t===d["default"].LEFT||t===d["default"].UP){e.preventDefault();var i=this.getNextActiveKey(!1);this.onTabClick(i)}},setActiveKey:function(e){this.state.activeKey!==e&&("activeKey"in this.props||this.setState({activeKey:e}),this.props.onChange(e))},getNextActiveKey:function(e){var t=this.state.activeKey,n=[];u["default"].Children.forEach(this.props.children,function(t){t&&!t.props.disabled&&(e?n.push(t):n.unshift(t))});var i=n.length,r=i&&n[0].key;return n.forEach(function(e,o){e.key===t&&(r=o===i-1?n[0].key:n[o+1].key)}),r},render:function(){var e,t=this.props,n=t.prefixCls,i=t.tabBarPosition,r=t.className,o=t.renderTabContent,a=t.renderTabBar,l=(0,m["default"])((e={},(0,s["default"])(e,n,1),(0,s["default"])(e,n+"-"+i,1),(0,s["default"])(e,r,!!r),e));this.tabBar=a();var c=[u["default"].cloneElement(this.tabBar,{prefixCls:n,key:"tabBar",onKeyDown:this.onNavKeyDown,tabBarPosition:i,onTabClick:this.onTabClick,panels:t.children,activeKey:this.state.activeKey}),u["default"].cloneElement(o(),{prefixCls:n,tabBarPosition:i,activeKey:this.state.activeKey,destroyInactiveTabPane:t.destroyInactiveTabPane,children:t.children,onChange:this.setActiveKey,key:"tabContent"})];return"bottom"===i&&c.reverse(),u["default"].createElement("div",{className:l,style:t.style},c)}});y.TabPane=p["default"],t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n={};for(var i in e)t.indexOf(i)>=0||Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},a=n(1),s=i(a),l=n(395),u=n(399),c=i(u),d=s["default"].createClass({displayName:"Tooltip",propTypes:{trigger:a.PropTypes.any,children:a.PropTypes.any,defaultVisible:a.PropTypes.bool,visible:a.PropTypes.bool,placement:a.PropTypes.string,transitionName:a.PropTypes.string,animation:a.PropTypes.any,onVisibleChange:a.PropTypes.func,afterVisibleChange:a.PropTypes.func,overlay:a.PropTypes.oneOfType([s["default"].PropTypes.node,s["default"].PropTypes.func]).isRequired,overlayStyle:a.PropTypes.object,overlayClassName:a.PropTypes.string,prefixCls:a.PropTypes.string,mouseEnterDelay:a.PropTypes.number,mouseLeaveDelay:a.PropTypes.number,getTooltipContainer:a.PropTypes.func,destroyTooltipOnHide:a.PropTypes.bool,align:a.PropTypes.object,arrowContent:a.PropTypes.any},getDefaultProps:function(){return{prefixCls:"rc-tooltip",mouseEnterDelay:0,destroyTooltipOnHide:!1,mouseLeaveDelay:.1,align:{},placement:"right",trigger:["hover"],arrowContent:null}},getPopupElement:function(){var e=this.props,t=e.arrowContent,n=e.overlay,i=e.prefixCls;return[s["default"].createElement("div",{className:i+"-arrow",key:"arrow"},t),s["default"].createElement("div",{className:i+"-inner",key:"content"},"function"==typeof n?n():n)]},getPopupDomNode:function(){return this.refs.trigger.getPopupDomNode()},render:function(){var e=this.props,t=e.overlayClassName,n=e.trigger,i=e.mouseEnterDelay,a=e.mouseLeaveDelay,u=e.overlayStyle,d=e.prefixCls,f=e.children,p=e.onVisibleChange,h=e.transitionName,m=e.animation,y=e.placement,v=e.align,g=e.destroyTooltipOnHide,b=e.defaultVisible,M=e.getTooltipContainer,T=r(e,["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","children","onVisibleChange","transitionName","animation","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer"]),x=o({},T);return"visible"in this.props&&(x.popupVisible=this.props.visible),s["default"].createElement(c["default"],o({popupClassName:t,ref:"trigger",prefixCls:d,popup:this.getPopupElement,action:n,builtinPlacements:l.placements,popupPlacement:y,popupAlign:v,getPopupContainer:M,onPopupVisibleChange:p,popupTransitionName:h,popupAnimation:m,defaultPopupVisible:b,destroyPopupOnHide:g,mouseLeaveDelay:a,popupStyle:u,mouseEnterDelay:i},x),f)}});t["default"]=d,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},i=[0,0],r=t.placements={left:{points:["cr","cl"],overflow:n,offset:[-4,0],targetOffset:i},right:{points:["cl","cr"],overflow:n,offset:[4,0],targetOffset:i},top:{points:["bc","tc"],overflow:n,offset:[0,-4],targetOffset:i},bottom:{points:["tc","bc"],overflow:n,offset:[0,4],targetOffset:i},topLeft:{points:["bl","tl"],overflow:n,offset:[0,-4],targetOffset:i},leftTop:{points:["tr","tl"],overflow:n,offset:[-4,0],targetOffset:i},topRight:{points:["br","tr"],overflow:n,offset:[0,-4],targetOffset:i},rightTop:{points:["tl","tr"],overflow:n,offset:[4,0],targetOffset:i},bottomRight:{points:["tr","br"],overflow:n,offset:[0,4],targetOffset:i},rightBottom:{points:["bl","br"],overflow:n,offset:[4,0],targetOffset:i},bottomLeft:{points:["tl","bl"],overflow:n,offset:[0,4],targetOffset:i},leftBottom:{points:["br","bl"],overflow:n,offset:[-4,0],targetOffset:i}};t["default"]=r},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(1),s=i(a),l=n(9),u=i(l),c=n(342),d=i(c),f=n(45),p=i(f),h=n(397),m=i(h),y=n(114),v=i(y),g=s["default"].createClass({displayName:"Popup",propTypes:{visible:a.PropTypes.bool,style:a.PropTypes.object,getClassNameFromAlign:a.PropTypes.func,onAlign:a.PropTypes.func,getRootDomNode:a.PropTypes.func,onMouseEnter:a.PropTypes.func,align:a.PropTypes.any,destroyPopupOnHide:a.PropTypes.bool,className:a.PropTypes.string,prefixCls:a.PropTypes.string,onMouseLeave:a.PropTypes.func},componentDidMount:function(){this.rootNode=this.getPopupDomNode()},onAlign:function(e,t){var n=this.props,i=n.getClassNameFromAlign(n.align),r=n.getClassNameFromAlign(t);i!==r&&(this.currentAlignClassName=r,e.className=this.getClassName(r)),n.onAlign(e,t)},getPopupDomNode:function(){return u["default"].findDOMNode(this.refs.popup)},getTarget:function(){return this.props.getRootDomNode()},getMaskTransitionName:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},getClassName:function(e){return this.props.prefixCls+" "+this.props.className+" "+e},getPopupElement:function(){var e=this.props,t=e.align,n=e.style,i=e.visible,r=e.prefixCls,a=e.destroyPopupOnHide,l=this.getClassName(this.currentAlignClassName||e.getClassNameFromAlign(t)),u=r+"-hidden";i||(this.currentAlignClassName=null);var c=(0,o["default"])({},n,this.getZIndexStyle()),f={className:l,prefixCls:r,ref:"popup",onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:c};return a?s["default"].createElement(p["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName()},i?s["default"].createElement(d["default"],{target:this.getTarget,key:"popup",ref:this.saveAlign,monitorWindowResize:!0,align:t,onAlign:this.onAlign},s["default"].createElement(m["default"],(0,o["default"])({visible:!0},f),e.children)):null):s["default"].createElement(p["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName(),showProp:"xVisible"},s["default"].createElement(d["default"],{target:this.getTarget,key:"popup",ref:this.saveAlign,monitorWindowResize:!0,xVisible:i,childrenProps:{visible:"xVisible"},disabled:!i,align:t,onAlign:this.onAlign},s["default"].createElement(m["default"],(0,o["default"])({hiddenClassName:u},f),e.children)))},getZIndexStyle:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getMaskElement:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=s["default"].createElement(v["default"],{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=s["default"].createElement(p["default"],{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},saveAlign:function(e){this.alignInstance=e},render:function(){return s["default"].createElement("div",null,this.getMaskElement(),this.getPopupElement())}});t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(114),s=i(a),l=o["default"].createClass({displayName:"PopupInner",propTypes:{hiddenClassName:r.PropTypes.string,className:r.PropTypes.string,prefixCls:r.PropTypes.string,onMouseEnter:r.PropTypes.func,onMouseLeave:r.PropTypes.func,children:r.PropTypes.any},render:function(){var e=this.props,t=e.className;return e.visible||(t+=" "+e.hiddenClassName),o["default"].createElement("div",{className:t,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:e.style},o["default"].createElement(s["default"],{className:e.prefixCls+"-content",visible:e.visible},e.children))}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}function o(){return""}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),s=i(a),l=n(1),u=i(l),c=n(9),d=i(c),f=n(402),p=i(f),h=n(401),m=i(h),y=n(396),v=i(y),g=n(400),b=n(403),M=i(b),T=["onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur"],x=u["default"].createClass({displayName:"Trigger",propTypes:{children:l.PropTypes.any,action:l.PropTypes.oneOfType([l.PropTypes.string,l.PropTypes.arrayOf(l.PropTypes.string)]),showAction:l.PropTypes.any,hideAction:l.PropTypes.any,getPopupClassNameFromAlign:l.PropTypes.any,onPopupVisibleChange:l.PropTypes.func,afterPopupVisibleChange:l.PropTypes.func,popup:l.PropTypes.oneOfType([l.PropTypes.node,l.PropTypes.func]).isRequired,popupStyle:l.PropTypes.object,prefixCls:l.PropTypes.string,popupClassName:l.PropTypes.string,popupPlacement:l.PropTypes.string,builtinPlacements:l.PropTypes.object,popupTransitionName:l.PropTypes.string,popupAnimation:l.PropTypes.any,mouseEnterDelay:l.PropTypes.number,mouseLeaveDelay:l.PropTypes.number,zIndex:l.PropTypes.number,focusDelay:l.PropTypes.number,blurDelay:l.PropTypes.number,getPopupContainer:l.PropTypes.func,destroyPopupOnHide:l.PropTypes.bool,mask:l.PropTypes.bool,maskClosable:l.PropTypes.bool,onPopupAlign:l.PropTypes.func,popupAlign:l.PropTypes.object,popupVisible:l.PropTypes.bool,maskTransitionName:l.PropTypes.string,maskAnimation:l.PropTypes.string},mixins:[(0,M["default"])({autoMount:!1,isVisible:function(e){return e.state.popupVisible},getContainer:function(e){var t=document.createElement("div"),n=e.props.getPopupContainer?e.props.getPopupContainer((0,c.findDOMNode)(e)):document.body;return n.appendChild(t),t},getComponent:function(e){var t=e.props,n=e.state,i={};return e.isMouseEnterToShow()&&(i.onMouseEnter=e.onPopupMouseEnter),e.isMouseLeaveToHide()&&(i.onMouseLeave=e.onPopupMouseLeave),u["default"].createElement(v["default"],(0,s["default"])({prefixCls:t.prefixCls,destroyPopupOnHide:t.destroyPopupOnHide,visible:n.popupVisible,className:t.popupClassName,action:t.action,align:e.getPopupAlign(),onAlign:t.onPopupAlign,animation:t.popupAnimation,getClassNameFromAlign:e.getPopupClassNameFromAlign},i,{getRootDomNode:e.getRootDomNode,style:t.popupStyle,mask:t.mask,zIndex:t.zIndex,transitionName:t.popupTransitionName,maskAnimation:t.maskAnimation,maskTransitionName:t.maskTransitionName}),"function"==typeof t.popup?t.popup():t.popup)}})],getDefaultProps:function(){return{prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:o,onPopupVisibleChange:r,afterPopupVisibleChange:r,onPopupAlign:r,popupClassName:"",mouseEnterDelay:0,mouseLeaveDelay:.1,focusDelay:0,blurDelay:.15,popupStyle:{},destroyPopupOnHide:!1,popupAlign:{},defaultPopupVisible:!1,mask:!1,maskClosable:!0,action:[],showAction:[],hideAction:[]}},getInitialState:function(){var e=this.props,t=void 0;return t="popupVisible"in e?!!e.popupVisible:!!e.defaultPopupVisible,{popupVisible:t}},componentWillMount:function(){var e=this;T.forEach(function(t){e["fire"+t]=function(n){e.fireEvents(t,n)}})},componentDidMount:function(){this.componentDidUpdate({},{popupVisible:this.state.popupVisible})},componentWillReceiveProps:function(e){var t=e.popupVisible;void 0!==t&&this.setState({popupVisible:t})},componentDidUpdate:function(e,t){var n=this.props,i=this.state;return this.renderComponent(null,function(){t.popupVisible!==i.popupVisible&&n.afterPopupVisibleChange(i.popupVisible)}),this.isClickToHide()&&i.popupVisible?void(this.clickOutsideHandler||(this.clickOutsideHandler=(0,m["default"])(document,"mousedown",this.onDocumentClick),this.touchOutsideHandler=(0,m["default"])(document,"touchstart",this.onDocumentClick))):void(this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.touchOutsideHandler.remove(),this.clickOutsideHandler=null,this.touchOutsideHandler=null))},componentWillUnmount:function(){this.clearDelayTimer(),this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.touchOutsideHandler.remove(),this.clickOutsideHandler=null,this.touchOutsideHandler=null)},onMouseEnter:function(e){this.fireEvents("onMouseEnter",e),this.delaySetPopupVisible(!0,this.props.mouseEnterDelay)},onMouseLeave:function(e){this.fireEvents("onMouseLeave",e),this.delaySetPopupVisible(!1,this.props.mouseLeaveDelay)},onPopupMouseEnter:function(){this.clearDelayTimer()},onPopupMouseLeave:function(e){e.relatedTarget&&!e.relatedTarget.setTimeout&&this._component&&(0,p["default"])(this._component.getPopupDomNode(),e.relatedTarget)||this.delaySetPopupVisible(!1,this.props.mouseLeaveDelay)},onFocus:function(e){this.fireEvents("onFocus",e),this.clearDelayTimer(),this.isFocusToShow()&&(this.focusTime=Date.now(),this.delaySetPopupVisible(!0,this.props.focusDelay))},onMouseDown:function(e){this.fireEvents("onMouseDown",e),this.preClickTime=Date.now()},onTouchStart:function(e){this.fireEvents("onTouchStart",e),this.preTouchTime=Date.now()},onBlur:function(e){this.fireEvents("onBlur",e),this.clearDelayTimer(),this.isBlurToHide()&&this.delaySetPopupVisible(!1,this.props.blurDelay)},onClick:function(e){if(this.fireEvents("onClick",e),this.focusTime){var t=void 0;if(this.preClickTime&&this.preTouchTime?t=Math.min(this.preClickTime,this.preTouchTime):this.preClickTime?t=this.preClickTime:this.preTouchTime&&(t=this.preTouchTime),Math.abs(t-this.focusTime)<20)return;this.focusTime=0}this.preClickTime=0,this.preTouchTime=0,e.preventDefault();var n=!this.state.popupVisible;(this.isClickToHide()&&!n||n&&this.isClickToShow())&&this.setPopupVisible(!this.state.popupVisible)},onDocumentClick:function(e){if(!this.props.mask||this.props.maskClosable){var t=e.target,n=(0,c.findDOMNode)(this),i=this.getPopupDomNode();(0,p["default"])(n,t)||(0,p["default"])(i,t)||this.close()}},getPopupDomNode:function(){return this._component&&this._component.isMounted()?this._component.getPopupDomNode():null},getRootDomNode:function(){return d["default"].findDOMNode(this)},getPopupClassNameFromAlign:function(e){var t=[],n=this.props,i=n.popupPlacement,r=n.builtinPlacements,o=n.prefixCls;return i&&r&&t.push((0,g.getPopupClassNameFromAlign)(r,o,e)),n.getPopupClassNameFromAlign&&t.push(n.getPopupClassNameFromAlign(e)),t.join(" ")},getPopupAlign:function(){var e=this.props,t=e.popupPlacement,n=e.popupAlign,i=e.builtinPlacements;return t&&i?(0,g.getAlignFromPlacement)(i,t,n):n},setPopupVisible:function(e){this.clearDelayTimer(),this.state.popupVisible!==e&&("popupVisible"in this.props||this.setState({popupVisible:e}),this.props.onPopupVisibleChange(e))},delaySetPopupVisible:function(e,t){var n=this,i=1e3*t;this.clearDelayTimer(),i?this.delayTimer=setTimeout(function(){n.setPopupVisible(e),n.clearDelayTimer()},i):this.setPopupVisible(e)},clearDelayTimer:function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},createTwoChains:function(e){var t=this.props.children.props,n=this.props;return t[e]&&n[e]?this["fire"+e]:t[e]||n[e]},isClickToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("click")!==-1||n.indexOf("click")!==-1},isClickToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("click")!==-1||n.indexOf("click")!==-1},isMouseEnterToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("hover")!==-1||n.indexOf("mouseEnter")!==-1},isMouseLeaveToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("hover")!==-1||n.indexOf("mouseLeave")!==-1},isFocusToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("focus")!==-1||n.indexOf("focus")!==-1},isBlurToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("focus")!==-1||n.indexOf("blur")!==-1},forcePopupAlign:function(){this.state.popupVisible&&this.popupInstance&&this.popupInstance.alignInstance&&this.popupInstance.alignInstance.forceAlign()},fireEvents:function(e,t){var n=this.props.children.props[e];n&&n(t);var i=this.props[e];i&&i(t)},close:function(){this.setPopupVisible(!1)},render:function(){var e=this.props,t=e.children,n=u["default"].Children.only(t),i={};return this.isClickToHide()||this.isClickToShow()?(i.onClick=this.onClick,i.onMouseDown=this.onMouseDown,i.onTouchStart=this.onTouchStart):(i.onClick=this.createTwoChains("onClick"),i.onMouseDown=this.createTwoChains("onMouseDown"),i.onTouchStart=this.createTwoChains("onTouchStart")),this.isMouseEnterToShow()?i.onMouseEnter=this.onMouseEnter:i.onMouseEnter=this.createTwoChains("onMouseEnter"),this.isMouseLeaveToHide()?i.onMouseLeave=this.onMouseLeave:i.onMouseLeave=this.createTwoChains("onMouseLeave"),this.isFocusToShow()||this.isBlurToHide()?(i.onFocus=this.onFocus,i.onBlur=this.onBlur):(i.onFocus=this.createTwoChains("onFocus"),i.onBlur=this.createTwoChains("onBlur")),u["default"].cloneElement(n,i)}});t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(398)},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){return e[0]===t[0]&&e[1]===t[1]}function o(e,t,n){var i=e[t]||{};return(0,l["default"])({},i,n)}function a(e,t,n){var i=n.points;for(var o in e)if(e.hasOwnProperty(o)&&r(e[o].points,i))return t+"-placement-"+o;return""}Object.defineProperty(t,"__esModule",{value:!0});var s=n(7),l=i(s);t.getAlignFromPlacement=o,t.getPopupClassNameFromAlign=a},344,function(e,t){"use strict";e.exports=function(e,t){for(var n=t;n;){if(n===e)return!0;n=n.parentNode}return!1}},357,function(e,t,n){"use strict";function i(e,t,n){return!r(e.props,t)||!r(e.state,n)}var r=n(39),o={shouldComponentUpdate:function(e,t){return i(this,e,t)}};e.exports=o},function(e,t,n){function i(e){var t=e.getDefaultProps;t&&(e.defaultProps=t(),delete e.getDefaultProps)}function r(e){function t(e){var t=e.state||{};s(t,n.call(e)),e.state=t}var n=e.getInitialState,i=e.componentWillMount;n&&(i?e.componentWillMount=function(){t(this),i.call(this)}:e.componentWillMount=function(){t(this)},delete e.getInitialState)}function o(e,t){i(t),r(t);var n={},s={};Object.keys(t).forEach(function(e){"mixins"!==e&&"statics"!==e&&("function"==typeof t[e]?n[e]=t[e]:s[e]=t[e])}),l(e.prototype,n);var u=function(e,t,n){if(!e)return t;if(!t)return e;var i={};return Object.keys(e).forEach(function(n){t[n]||(i[n]=e[n])}),Object.keys(t).forEach(function(n){e[n]?i[n]=function(){return t[n].apply(this,arguments)&&e[n].apply(this,arguments)}:i[n]=t[n]}),i};return a({childContextTypes:u,contextTypes:u,propTypes:a.MANY_MERGED_LOOSE,defaultProps:a.MANY_MERGED_LOOSE})(e,s),t.statics&&Object.getOwnPropertyNames(t.statics).forEach(function(n){var i=e[n],r=t.statics[n];if(void 0!==i&&void 0!==r)throw new TypeError("Cannot mixin statics because statics."+n+" and Component."+n+" are defined.");e[n]=void 0!==i?i:r}),t.mixins&&t.mixins.reverse().forEach(o.bind(null,e)),e}var a=n(428),s=n(10),l=a({componentDidMount:a.MANY,componentWillMount:a.MANY,componentWillReceiveProps:a.MANY,shouldComponentUpdate:a.ONCE,componentWillUpdate:a.MANY,componentDidUpdate:a.MANY,componentWillUnmount:a.MANY,getChildContext:a.MANY_MERGED});e.exports=function(){var e=l;return e.onClass=function(e,t){return t=s({},t),o(e,t)},e.decorate=function(t){return function(n){return e.onClass(n,t)}},e}()},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}(),l=n(1),u=i(l),c=n(9),d=i(c),f=n(115),p=i(f),h=function(e){function t(e){r(this,t);var n=o(this,Object.getPrototypeOf(t).call(this,e));return n.updateOffset=function(e){var t=e.inherited,i=e.offset;n.channel.update(function(e){e.inherited=t+i})},n.channel=new p["default"]({inherited:0,offset:0,node:null}),n}return a(t,e),s(t,[{key:"getChildContext",value:function(){return{"sticky-channel":this.channel}}},{key:"componentWillMount",value:function(){var e=this.context["sticky-channel"];e&&e.subscribe(this.updateOffset)}},{key:"componentDidMount",value:function(){var e=d["default"].findDOMNode(this);this.channel.update(function(t){t.node=e})}},{key:"componentWillUnmount",value:function(){this.channel.update(function(e){e.node=null});var e=this.context["sticky-channel"];e&&e.unsubscribe(this.updateOffset)}},{key:"render",value:function(){return u["default"].createElement("div",this.props,this.props.children)}}]),t}(u["default"].Component);h.contextTypes={"sticky-channel":u["default"].PropTypes.any},h.childContextTypes={"sticky-channel":u["default"].PropTypes.any},t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Channel=t.StickyContainer=t.Sticky=void 0;var r=n(408),o=i(r),a=n(406),s=i(a),l=n(115),u=i(l);t.Sticky=o["default"],t.StickyContainer=s["default"],t.Channel=u["default"],t["default"]=o["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n={};for(var i in e)t.indexOf(i)>=0||Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},u=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}(),c=n(1),d=i(c),f=n(9),p=i(f),h=function(e){function t(e){o(this,t);var n=a(this,Object.getPrototypeOf(t).call(this,e));return n.updateContext=function(e){var t=e.inherited,i=e.node;n.containerNode=i,n.setState({containerOffset:t,distanceFromBottom:n.getDistanceFromBottom()})},n.recomputeState=function(){var e=n.isSticky(),t=n.getHeight(),i=n.getWidth(),r=n.getXOffset(),o=n.getDistanceFromBottom(),a=n.state.isSticky!==e;n.setState({isSticky:e,height:t,width:i,xOffset:r,distanceFromBottom:o}),a&&(n.channel&&n.channel.update(function(t){t.offset=e?n.state.height:0}),n.props.onStickyStateChange(e))},n.state={},n}return s(t,e),u(t,[{key:"componentWillMount",value:function(){this.channel=this.context["sticky-channel"],this.channel.subscribe(this.updateContext)}},{key:"componentDidMount",value:function(){this.on(["resize","scroll","touchstart","touchmove","touchend","pageshow","load"],this.recomputeState),this.recomputeState()}},{key:"componentWillReceiveProps",value:function(){this.recomputeState()}},{key:"componentWillUnmount",value:function(){this.off(["resize","scroll","touchstart","touchmove","touchend","pageshow","load"],this.recomputeState),this.channel.unsubscribe(this.updateContext)}},{key:"getXOffset",value:function(){return this.refs.placeholder.getBoundingClientRect().left}},{key:"getWidth",value:function(){return this.refs.placeholder.getBoundingClientRect().width}},{key:"getHeight",value:function(){return p["default"].findDOMNode(this.refs.children).getBoundingClientRect().height}},{key:"getDistanceFromTop",value:function(){return this.refs.placeholder.getBoundingClientRect().top}},{key:"getDistanceFromBottom",value:function(){return this.containerNode?this.containerNode.getBoundingClientRect().bottom:0}},{key:"isSticky",value:function(){if(!this.props.isActive)return!1;var e=this.getDistanceFromTop(),t=this.getDistanceFromBottom(),n=this.state.containerOffset-this.props.topOffset,i=this.state.containerOffset+this.props.bottomOffset;return e<=n&&t>=i}},{key:"on",value:function(e,t){e.forEach(function(e){window.addEventListener(e,t)})}},{key:"off",value:function(e,t){e.forEach(function(e){window.removeEventListener(e,t)})}},{key:"shouldComponentUpdate",value:function(e,t){var n=this,i=Object.keys(this.props);if(Object.keys(e).length!=i.length)return!0;var r=i.every(function(t){return e.hasOwnProperty(t)&&e[t]===n.props[t]});if(!r)return!0;var o=this.state;if(t.isSticky!==o.isSticky)return!0;if(o.isSticky){if(t.height!==o.height)return!0;if(t.width!==o.width)return!0;if(t.xOffset!==o.xOffset)return!0; if(t.containerOffset!==o.containerOffset)return!0;if(t.distanceFromBottom!==o.distanceFromBottom)return!0}return!1}},{key:"render",value:function(){var e={paddingBottom:0},t=this.props.className,n=l({},{transform:"translateZ(0)"},this.props.style);if(this.state.isSticky){var i={position:"fixed",top:this.state.containerOffset,left:this.state.xOffset,width:this.state.width},o=this.state.distanceFromBottom-this.state.height-this.props.bottomOffset;this.state.containerOffset>o&&(i.top=o),e.paddingBottom=this.state.height,t+=" "+this.props.stickyClassName,n=l({},n,i,this.props.stickyStyle)}var a=this.props,s=(a.topOffset,a.isActive,a.stickyClassName,a.stickyStyle,a.bottomOffset,a.onStickyStateChange,r(a,["topOffset","isActive","stickyClassName","stickyStyle","bottomOffset","onStickyStateChange"]));return d["default"].createElement("div",null,d["default"].createElement("div",{ref:"placeholder",style:e}),d["default"].createElement("div",l({},s,{ref:"children",className:t,style:n}),this.props.children))}}]),t}(d["default"].Component);h.propTypes={isActive:d["default"].PropTypes.bool,className:d["default"].PropTypes.string,style:d["default"].PropTypes.object,stickyClassName:d["default"].PropTypes.string,stickyStyle:d["default"].PropTypes.object,topOffset:d["default"].PropTypes.number,bottomOffset:d["default"].PropTypes.number,onStickyStateChange:d["default"].PropTypes.func},h.defaultProps={isActive:!0,className:"",style:{},stickyClassName:"sticky",stickyStyle:{},topOffset:0,bottomOffset:0,onStickyStateChange:function(){}},h.contextTypes={"sticky-channel":d["default"].PropTypes.any},t["default"]=h,e.exports=t["default"]},function(e,t){(function(t){"use strict";var n="undefined"==typeof window?t:window,i=function(e,t,n){return function(i,r){var o=e(function(){t.call(this,o),i.apply(this,arguments)}.bind(this),r);return this[n]?this[n].push(o):this[n]=[o],o}},r=function(e,t){return function(n){if(this[t]){var i=this[t].indexOf(n);i!==-1&&this[t].splice(i,1)}e(n)}},o="TimerMixin_timeouts",a=r(n.clearTimeout,o),s=i(n.setTimeout,a,o),l="TimerMixin_intervals",u=r(n.clearInterval,l),c=i(n.setInterval,function(){},l),d="TimerMixin_immediates",f=r(n.clearImmediate,d),p=i(n.setImmediate,f,d),h="TimerMixin_rafs",m=r(n.cancelAnimationFrame,h),y=i(n.requestAnimationFrame,m,h),v={componentWillUnmount:function(){this[o]&&this[o].forEach(function(e){n.clearTimeout(e)}),this[o]=null,this[l]&&this[l].forEach(function(e){n.clearInterval(e)}),this[l]=null,this[d]&&this[d].forEach(function(e){n.clearImmediate(e)}),this[d]=null,this[h]&&this[h].forEach(function(e){n.cancelAnimationFrame(e)}),this[h]=null},setTimeout:s,clearTimeout:a,setInterval:c,clearInterval:u,setImmediate:p,clearImmediate:f,requestAnimationFrame:y,cancelAnimationFrame:m};e.exports=v}).call(t,function(){return this}())},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=i(r),a=n(5),s=i(a),l=n(117),u=i(l),c=n(411),d=i(c),f=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},p=o["default"].createClass({displayName:"Cascader",mixins:[d["default"]],getDefaultProps:function(){return{prefixCls:"rmc-cascader",pickerPrefixCls:"rmc-picker",data:[],disabled:!1}},render:function(){var e=this,t=this.props,n=t.prefixCls,i=t.pickerPrefixCls,r=t.className,a=t.rootNativeProps,l=t.disabled,c=t.pickerItemStyle,d=this.state.value,p=this.getChildrenTree(),h=this.getColArray().map(function(t,r){return o["default"].createElement("div",{key:r,className:n+"-item "+n+"-main-item"},o["default"].createElement(u["default"],{itemStyle:c,disabled:l,prefixCls:i,selectedValue:d[r],onValueChange:e.onValueChange.bind(e,r)},p[r]||[]))});return o["default"].createElement("div",f({},a,{className:(0,s["default"])(r,n)}),h)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(74),o=i(r);t["default"]={getDefaultProps:function(){return{cols:3}},getInitialState:function(){return{value:this.getValue(this.props.data,this.props.defaultValue||this.props.value)}},componentWillReceiveProps:function(e){"value"in e&&this.setState({value:this.getValue(e.data,e.value)})},onValueChange:function(e,t){var n=this.state.value.concat();n[e]=t;var i=(0,o["default"])(this.props.data,function(t,i){return i<=e&&t.value===n[i]}),r=i[e],a=void 0;for(a=e+1;r&&r.children&&r.children.length&&a<this.props.cols;a++)r=r.children[0],n[a]=r.value;n.length=a,"value"in this.props||this.setState({value:n}),this.props.onChange(n)},getValue:function(e,t){var n=e||this.props.data,i=t||this.props.value||this.props.defaultValue;if(!i||!i.length){i=[];for(var r=0;r<this.props.cols;r++)n&&n.length?(i[r]=n[0].value,n=n[0].children):i[r]=void 0}return i},getColArray:function(){for(var e=[],t=0;t<this.props.cols;t++)e[t]=void 0;return e},getChildrenTree:function(){var e=this.props,t=e.data,n=e.cols,i=this.state.value,r=(0,o["default"])(t,function(e,t){return e.value===i[t]}).map(function(e){return e.children});return r.length=n-1,r.unshift(t),r}},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=i(o),s=n(4),l=i(s),u=n(3),c=i(u),d=n(1),f=i(d),p=n(118),h=i(p),m=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e},y=function(e){function t(n){(0,a["default"])(this,t);var i=(0,l["default"])(this,e.call(this,n));return i.onPickerChange=function(e){i.setState({pickerValue:e}),i.props.cascader.props.onChange&&i.props.cascader.props.onChange(e)},i.onOk=function(){var e=i.props.onChange;e&&e(i.cascader.getValue().filter(function(e){return null!==e&&void 0!==e}))},i.saveRef=function(e){i.cascader=e},i.fireVisibleChange=function(e){if(i.state.visible!==e){"visible"in i.props||i.setVisibleState(e);var t=i.props.onVisibleChange;t&&t(e)}},i.state={pickerValue:null,visible:i.props.visible||!1},i}return(0,c["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"visible"in e&&this.setVisibleState(e.visible)},t.prototype.setVisibleState=function(e){this.setState({visible:e}),e||this.setState({pickerValue:null})},t.prototype.render=function(){var e=f["default"].cloneElement(this.props.cascader,{value:this.state.pickerValue||this.props.value,onChange:this.onPickerChange,ref:this.saveRef,data:this.props.cascader.props.data});return f["default"].createElement(h["default"],m({},this.props,{onVisibleChange:this.fireVisibleChange,onOk:this.onOk,content:e,visible:this.state.visible}))},t}(f["default"].Component);t["default"]=y,y.defaultProps={prefixCls:"rmc-picker-popup",onVisibleChange:r,onChange:r},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(1),s=i(a),l=n(426),u=i(l),c=n(5),d=i(c),f=n(414),p=i(f),h=s["default"].createClass({displayName:"DatePickerWeb",mixins:[p["default"]],getDefaultProps:function(){return{prefixCls:"rmc-date-picker",pickerPrefixCls:"rmc-picker",disabled:!1}},render:function(){var e=this,t=this.props,n=t.prefixCls,i=t.pickerPrefixCls,r=t.className,a=t.rootNativeProps,l=t.disabled,c=this.getValueDataSource(),f=c.value,p=c.dataSource,h=p.map(function(t,r){return s["default"].createElement("div",{key:r,className:n+"-item"},s["default"].createElement(u["default"],{disabled:l,prefixCls:i,pure:!1,selectedValue:f[r],onValueChange:function(t){e.onValueChange(r,t)}},t))});return s["default"].createElement("div",(0,o["default"])({},a,{className:(0,d["default"])(r,n)}),h)}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return e.clone().year(t).month(n).endOf("month").date()}Object.defineProperty(t,"__esModule",{value:!0});var o=n(53),a=i(o),s=n(106),l=i(s),u=n(416),c=i(u),d="datetime",f="date",p="time";t["default"]={getDefaultProps:function(){return{locale:c["default"],mode:f,onDateChange:function(){}}},getInitialState:function(){return{date:this.props.date||this.props.defaultDate}},componentWillReceiveProps:function(e){"date"in e&&this.setState({date:e.date||e.defaultDate})},onValueChange:function(e,t){var n=this.props,i=this.getDate().clone();if(n.mode===d||n.mode===f)switch(e){case 0:i.year(t);break;case 1:i.month(t);break;case 2:i.date(t);break;case 3:i.hour(t);break;case 4:i.minute(t)}else switch(e){case 0:i.hour(t);break;case 1:i.minute(t)}i=this.clipDate(i),"date"in this.props||this.setState({date:i}),n.onDateChange(i)},getDefaultMinDate:function(){return this.defaultMinDate||(this.defaultMinDate=this.getGregorianCalendar([2e3,1,1,0,0,0])),this.defaultMinDate},getDefaultMaxDate:function(){return this.defaultMaxDate||(this.defaultMaxDate=this.getGregorianCalendar([2030,1,1,23,59,59])),this.defaultMaxDate},getDate:function(){return this.state.date||this.getDefaultMinDate()},getMinYear:function(){return this.getMinDate().year()},getMaxYear:function(){return this.getMaxDate().year()},getMinMonth:function(){return this.getMinDate().month()},getMaxMonth:function(){return this.getMaxDate().month()},getMinDay:function(){return this.getMinDate().date()},getMaxDay:function(){return this.getMaxDate().date()},getMinHour:function(){return this.getMinDate().hour()},getMaxHour:function(){return this.getMaxDate().hour()},getMinMinute:function(){return this.getMinDate().minute()},getMaxMinute:function(){return this.getMaxDate().minute()},getMinDate:function(){return this.props.minDate||this.getDefaultMinDate()},getMaxDate:function(){return this.props.maxDate||this.getDefaultMaxDate()},getDateData:function(){for(var e=this.props.locale,t=this.getDate(),n=t.year(),i=t.month(),o=this.getMinYear(),a=this.getMaxYear(),s=this.getMinMonth(),l=this.getMaxMonth(),u=this.getMinDay(),c=this.getMaxDay(),d=[],f=o;f<=a;f++)d.push({value:f,label:f+e.year});var p=[],h=0,m=11;o===n&&(h=s),a===n&&(m=l);for(var y=h;y<=m;y++)p.push({value:y,label:y+1+e.month});var v=[],g=1,b=r(t,n,i);o===n&&s===i&&(g=u),a===n&&l===i&&(b=c);for(var M=g;M<=b;M++)v.push({value:M,label:M+e.day});return[d,p,v]},getTimeData:function(){var e=0,t=23,n=0,i=59,r=this.props,o=r.mode,a=r.locale,s=this.getDate(),l=this.getMinMinute(),u=this.getMaxMinute(),c=this.getMinHour(),f=this.getMaxHour(),p=s.hour();if(o===d){var h=s.year(),m=s.month(),y=s.date(),v=this.getMinYear(),g=this.getMaxYear(),b=this.getMinMonth(),M=this.getMaxMonth(),T=this.getMinDay(),x=this.getMaxDay();v===h&&b===m&&T===y&&(e=c,c===p&&(n=l)),g===h&&M===m&&x===y&&(t=f,f===p&&(i=u))}else e=c,c===p&&(n=l),t=f,f===p&&(i=u);for(var C=[],_=e;_<=t;_++)C.push({value:_,label:_+a.hour});for(var w=[],S=n;S<=i;S++)w.push({value:S,label:S+a.minute});return[C,w]},getGregorianCalendar:function(e){return(0,l["default"])(e)},clipDate:function(e){var t=this.props.mode,n=this.getMinDate(),i=this.getMaxDate();if(t===d){if(e.isBefore(n))return n.clone();if(e.isAfter(i))return i.clone()}else if(t===f){if(e.isBefore(n,"day")<0)return n.clone();if(e.isAfter(i,"day")>0)return i.clone()}else{var r=i.hour(),o=i.minute(),a=n.hour(),s=n.minute(),l=e.hour(),u=e.minute();if(l<a||l===a&&u<s)return n.clone();if(l>r||l===r&&u>o)return i.clone()}return e},getValueDataSource:function(){var e=this.props.mode,t=this.getDate(),n=[],i=[];return e!==d&&e!==f||(n=[].concat((0,a["default"])(this.getDateData())),i=[t.year(),t.month(),t.date()]),e!==d&&e!==p||(n=n.concat(this.getTimeData()),i=i.concat([t.hour(),t.minute()])),{value:i,dataSource:n}}},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(){}Object.defineProperty(t,"__esModule",{value:!0});var o=n(7),a=i(o),s=n(2),l=i(s),u=n(4),c=i(u),d=n(3),f=i(d),p=n(1),h=i(p),m=n(118),y=i(m),v=function(e){function t(n){(0,l["default"])(this,t);var i=(0,c["default"])(this,e.call(this,n));return i.onPickerChange=function(e){i.setState({pickerDate:e}),i.props.datePicker.props.onDateChange&&i.props.datePicker.props.onDateChange(e)},i.onOk=function(){var e=i.props.onChange;e&&e(i.datePicker.getDate())},i.saveRef=function(e){i.datePicker=e},i.fireVisibleChange=function(e){if(i.state.visible!==e){"visible"in i.props||i.setVisibleState(e);var t=i.props.onVisibleChange;t&&t(e)}},i.state={pickerDate:null,visible:i.props.visible||!1},i}return(0,f["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"visible"in e&&this.setVisibleState(e.visible)},t.prototype.setVisibleState=function(e){this.setState({visible:e}),e||this.setState({pickerDate:null})},t.prototype.render=function(){var e=h["default"].cloneElement(this.props.datePicker,{date:this.state.pickerDate||this.props.date,onDateChange:this.onPickerChange,ref:this.saveRef});return h["default"].createElement(y["default"],(0,a["default"])({},this.props,{onVisibleChange:this.fireVisibleChange,onOk:this.onOk,content:e,visible:this.state.visible}))},t}(h["default"].Component);t["default"]=v,v.defaultProps={onVisibleChange:r,prefixCls:"rmc-picker-popup",onChange:r,onDismiss:r,onPickerChange:r},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={year:"",month:"",day:"",hour:"",minute:""},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={year:"\u5e74",month:"\u6708",day:"\u65e5",hour:"\u65f6",minute:"\u5206"},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(7),o=i(r),a=n(6),s=i(a),l=n(52),u=i(l),c=n(2),d=i(c),f=n(4),p=i(f),h=n(3),m=i(h),y=n(1),v=i(y),g=n(9),b=i(g),M=n(5),T=i(M),x=n(116),C=i(x),_=n(73),w=function(e){function t(n){(0,d["default"])(this,t);var i=(0,p["default"])(this,e.call(this,n));return S.call(i),i.state={pageSize:n.pageSize,_delay:!1},i}return(0,m["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){this.props.dataSource!==e.dataSource&&this.dataChange(e)},t.prototype.componentWillUnmount=function(){this._timer&&clearTimeout(this._timer),this._hCache=null},t.prototype.componentDidUpdate=function(){this.getQsInfo()},t.prototype.componentDidMount=function(){this.dataChange(this.props),this.getQsInfo()},t.prototype.renderQuickSearchBar=function(e,t){var n=this,i=this.props,r=i.dataSource,o=i.prefixCls,a=r.sectionIdentities.map(function(e){return{value:e,label:r._getSectionHeaderData(r._dataBlob,e)}});return v["default"].createElement("ul",{ref:"quickSearchBar",className:o+"-quick-search-bar",style:t,onTouchStart:this.onTouchStart,onTouchMove:this.onTouchMove,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchEnd},v["default"].createElement("li",{"data-qf-target":e.value,onClick:function(){return n.onQuickSearchTop(void 0,e.value)}},e.label),a.map(function(e){return v["default"].createElement("li",{key:e.value,"data-qf-target":e.value,onClick:function(){return n.onQuickSearch(e.value)}},e.label)}))},t.prototype.render=function(){var e,t=this,n=this.state,i=n._delay,r=n.pageSize,a=this.props,l=a.className,c=a.prefixCls,d=a.children,f=a.quickSearchBarTop,p=a.quickSearchBarStyle,h=a.initialListSize,m=void 0===h?Math.min(20,this.props.dataSource.getRowCount()):h,y=a.renderSectionHeader,g=a.sectionHeaderClassName,b=(0,u["default"])(a,["className","prefixCls","children","quickSearchBarTop","quickSearchBarStyle","initialListSize","renderSectionHeader","sectionHeaderClassName"]),M=(0,T["default"])((e={},(0,s["default"])(e,l,l),(0,s["default"])(e,c,!0),e));return v["default"].createElement("div",{className:c+"-container"},i&&this.props.delayActivityIndicator,v["default"].createElement(C["default"],(0,o["default"])({},b,{ref:"indexedListView",className:M,initialListSize:m,pageSize:r,renderSectionHeader:function(e,n){return v["default"].cloneElement(y(e,n),{ref:function(e){return t.sectionComponents[n]=e},className:g||c+"-section-header"})}}),d),this.renderQuickSearchBar(f,p))},t}(v["default"].Component);w.propTypes={prefixCls:y.PropTypes.string,sectionHeaderClassName:y.PropTypes.string,quickSearchBarTop:y.PropTypes.object,onQuickSearch:y.PropTypes.func},w.defaultProps={prefixCls:"rmc-indexed-list",quickSearchBarTop:{value:"#",label:"#"},onQuickSearch:function(){},delayTime:100,delayActivityIndicator:""};var S=function(){var e=this;this.getQsInfo=function(){var t=e.refs.quickSearchBar,n=t.offsetHeight,i=[];[].slice.call(t.querySelectorAll("[data-qf-target]")).forEach(function(e){i.push([e])});for(var r=n/i.length,o=0,a=0,s=i.length;a<s;a++)o=a*r,i[a][1]=[o,o+r];e._qsHeight=n,e._avgH=r,e._hCache=i},this.dataChange=function(t){var n=t.dataSource.getRowCount();n&&(e.setState({_delay:!0}),e._timer&&clearTimeout(e._timer),e._timer=setTimeout(function(){e.setState({pageSize:n,_delay:!1},function(){return e.refs.indexedListView._pageInNewRows()})},t.delayTime))},this.sectionComponents={},this.onQuickSearchTop=function(t,n){e.props.stickyHeader?window.document.body.scrollTop=0:b["default"].findDOMNode(e.refs.indexedListView.refs.listviewscroll).scrollTop=0,e.props.onQuickSearch(t,n)},this.onQuickSearch=function(t){var n=b["default"].findDOMNode(e.refs.indexedListView.refs.listviewscroll),i=b["default"].findDOMNode(e.sectionComponents[t]);if(e.props.stickyHeader){var r=e.refs.indexedListView.stickyRefs[t];r&&r.refs.placeholder&&(i=b["default"].findDOMNode(r.refs.placeholder)),window.document.body.scrollTop=i.getBoundingClientRect().top-n.getBoundingClientRect().top+(0,_.getOffsetTop)(n)}else n.scrollTop+=i.getBoundingClientRect().top-n.getBoundingClientRect().top;e.props.onQuickSearch(t)},this.onTouchStart=function(t){e._target=t.target,e._basePos=e.refs.quickSearchBar.getBoundingClientRect(),document.addEventListener("touchmove",e._disableParent,!1),document.body.className=document.body.className+" "+e.props.prefixCls+"-qsb-moving",e.updateCls(e._target)},this.onTouchMove=function(t){if(t.preventDefault(),e._target){var n=(0,_._event)(t),i=e._basePos,r=void 0;if(n.clientY>=i.top&&n.clientY<=i.top+e._qsHeight){r=Math.floor((n.clientY-i.top)/e._avgH);var o=void 0;if(r in e._hCache&&(o=e._hCache[r][0]),o){var a=o.getAttribute("data-qf-target");e._target!==o&&(e.props.quickSearchBarTop.value===a?e.onQuickSearchTop(void 0,a):e.onQuickSearch(a),e.updateCls(o)),e._target=o}}}},this.onTouchEnd=function(t){e._target&&(document.removeEventListener("touchmove",e._disableParent,!1),document.body.className=document.body.className.replace(new RegExp(e.props.prefixCls+"-qsb-moving","g"),""),e.updateCls(e._target,!0),e._target=null)},this.updateCls=function(t,n){var i=e.props.prefixCls+"-quick-search-bar-over";e._hCache.forEach(function(e){e[0].className=e[0].className.replace(i,"")}),n||(t.className=t.className+" "+i)},this._disableParent=function(e){e.preventDefault(),e.stopPropagation()}};t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,n){return e[t][n]}function o(e,t){return e[t]}function a(e){for(var t=0,n=0;n<e.length;n++){var i=e[n];t+=i.length}return t}function s(e){if((0,p["default"])(e))return{};for(var t={},n=0;n<e.length;n++){var i=e[n];(0,m["default"])(!t[i],"Value appears more than once in array: "+i),t[i]=!0}return t}var l=n(2),u=i(l),c=n(104),d=i(c),f=n(326),p=i(f),h=n(105),m=i(h),y=function(){function e(t){(0,u["default"])(this,e),(0,d["default"])(t&&"function"==typeof t.rowHasChanged,"Must provide a rowHasChanged function."),this._rowHasChanged=t.rowHasChanged,this._getRowData=t.getRowData||r,this._sectionHeaderHasChanged=t.sectionHeaderHasChanged,this._getSectionHeaderData=t.getSectionHeaderData||o,this._dataBlob=null,this._dirtyRows=[],this._dirtySections=[],this._cachedRowCount=0,this.rowIdentities=[],this.sectionIdentities=[]}return e.prototype.cloneWithRows=function(e,t){var n=t?[t]:null;return this._sectionHeaderHasChanged||(this._sectionHeaderHasChanged=function(){return!1}),this.cloneWithRowsAndSections({s1:e},["s1"],n)},e.prototype.cloneWithRowsAndSections=function(t,n,i){(0,d["default"])("function"==typeof this._sectionHeaderHasChanged,"Must provide a sectionHeaderHasChanged function with section data."),(0,d["default"])(!n||!i||n.length===i.length,"row and section ids lengths must be the same");var r=new e({getRowData:this._getRowData,getSectionHeaderData:this._getSectionHeaderData,rowHasChanged:this._rowHasChanged,sectionHeaderHasChanged:this._sectionHeaderHasChanged});return r._dataBlob=t,n?r.sectionIdentities=n:r.sectionIdentities=Object.keys(t),i?r.rowIdentities=i:(r.rowIdentities=[],r.sectionIdentities.forEach(function(e){r.rowIdentities.push(Object.keys(t[e]))})),r._cachedRowCount=a(r.rowIdentities),r._calculateDirtyArrays(this._dataBlob,this.sectionIdentities,this.rowIdentities),r},e.prototype.getRowCount=function(){return this._cachedRowCount},e.prototype.getRowAndSectionCount=function(){return this._cachedRowCount+this.sectionIdentities.length},e.prototype.rowShouldUpdate=function(e,t){var n=this._dirtyRows[e][t];return(0,m["default"])(void 0!==n,"missing dirtyBit for section, row: "+e+", "+t),n},e.prototype.getRowData=function(e,t){var n=this.sectionIdentities[e],i=this.rowIdentities[e][t];return(0,m["default"])(void 0!==n&&void 0!==i,"rendering invalid section, row: "+e+", "+t),this._getRowData(this._dataBlob,n,i)},e.prototype.getRowIDForFlatIndex=function(e){for(var t=e,n=0;n<this.sectionIdentities.length;n++){if(!(t>=this.rowIdentities[n].length))return this.rowIdentities[n][t];t-=this.rowIdentities[n].length}return null},e.prototype.getSectionIDForFlatIndex=function(e){for(var t=e,n=0;n<this.sectionIdentities.length;n++){if(!(t>=this.rowIdentities[n].length))return this.sectionIdentities[n];t-=this.rowIdentities[n].length}return null},e.prototype.getSectionLengths=function(){for(var e=[],t=0;t<this.sectionIdentities.length;t++)e.push(this.rowIdentities[t].length);return e},e.prototype.sectionHeaderShouldUpdate=function(e){var t=this._dirtySections[e];return(0,m["default"])(void 0!==t,"missing dirtyBit for section: "+e),t},e.prototype.getSectionHeaderData=function(e){if(!this._getSectionHeaderData)return null;var t=this.sectionIdentities[e];return(0,m["default"])(void 0!==t,"renderSection called on invalid section: "+e),this._getSectionHeaderData(this._dataBlob,t)},e.prototype._calculateDirtyArrays=function(e,t,n){for(var i=s(t),r={},o=0;o<n.length;o++){var a=t[o];(0,m["default"])(!r[a],"SectionID appears more than once: "+a),r[a]=s(n[o])}this._dirtySections=[],this._dirtyRows=[];for(var l,u=0;u<this.sectionIdentities.length;u++){var a=this.sectionIdentities[u];l=!i[a];var c=this._sectionHeaderHasChanged;!l&&c&&(l=c(this._getSectionHeaderData(e,a),this._getSectionHeaderData(this._dataBlob,a))),this._dirtySections.push(!!l),this._dirtyRows[u]=[];for(var d=0;d<this.rowIdentities[u].length;d++){var f=this.rowIdentities[u][d];l=!i[a]||!r[a][f]||this._rowHasChanged(this._getRowData(e,a,f),this._getRowData(this._dataBlob,a,f)),this._dirtyRows[u].push(!!l)}}},e}();e.exports=y},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(1),o=(i(r),n(9)),a=i(o);t["default"]={bindEvt:function(){var e=this.getEle();e.addEventListener("touchstart",this.onPullUpStart),e.addEventListener("touchmove",this.onPullUpMove),e.addEventListener("touchend",this.onPullUpEnd),e.addEventListener("touchcancel",this.onPullUpEnd)},unBindEvt:function(){var e=this.getEle();e.removeEventListener("touchstart",this.onPullUpStart),e.removeEventListener("touchmove",this.onPullUpMove),e.removeEventListener("touchend",this.onPullUpEnd),e.removeEventListener("touchcancel",this.onPullUpEnd)},getEle:function(){var e=this.props,t=e.stickyHeader,n=e.useBodyScroll,i=(e.useZscroller,void 0);return i=t||n?document.body:a["default"].findDOMNode(this.refs.listviewscroll.refs.ScrollView)},componentDidMount:function(){this.bindEvt()},componentWillUnmount:function(){this.unBindEvt()},onPullUpStart:function(e){this._pullUpStartPageY=e.touches[0].screenY,this._isPullUp=!1,this._pullUpEle=this.getEle()},onPullUpMove:function(e){e.touches[0].screenY<this._pullUpStartPageY&&this._reachBottom()&&(this._isPullUp=!0)},onPullUpEnd:function(e){this._isPullUp&&this.props.onEndReached&&this.props.onEndReached(e),this._isPullUp=!1},_reachBottom:function(){var e=this._pullUpEle;return e===document.body?e.scrollHeight-e.scrollTop===window.innerHeight:e.scrollHeight-e.scrollTop===e.clientHeight}},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(6),o=i(r),a=n(1),s=i(a),l=n(9),u=(i(l),n(5)),c=i(u);t["default"]=s["default"].createClass({displayName:"RefreshControl",propTypes:{className:a.PropTypes.string,style:a.PropTypes.object,icon:a.PropTypes.element,prefixCls:a.PropTypes.string,loading:a.PropTypes.element,distanceToRefresh:a.PropTypes.number,refreshing:a.PropTypes.bool,onRefresh:a.PropTypes.func.isRequired},getInitialState:function(){return{active:!1,loadingState:!1}},getDefaultProps:function(){return{prefixCls:"list-view-refresh-control",distanceToRefresh:50,refreshing:!1,icon:s["default"].createElement("div",{style:{lineHeight:"50px",textAlign:"center"}},s["default"].createElement("div",{className:"list-view-refresh-control-pull"},"\u2193 \u4e0b\u62c9"),s["default"].createElement("div",{className:"list-view-refresh-control-release"},"\u2191 \u91ca\u653e")),loading:s["default"].createElement("div",{style:{lineHeight:"50px",textAlign:"center"}},"loading...")}},render:function(){var e,t=this.props,n=t.prefixCls,i=t.icon,r=t.loading,a=t.className,l=void 0===a?"":a,u=t.style,d=t.refreshing,f=this.state,p=f.active,h=f.loadingState,m=(0,c["default"])((e={},(0,o["default"])(e,l,l),(0,o["default"])(e,n+"-ptr",!0),(0,o["default"])(e,n+"-active",p),(0,o["default"])(e,n+"-loading",h||d),e));return s["default"].createElement("div",{ref:"ptr",className:m,style:u},s["default"].createElement("div",{className:n+"-ptr-icon"},i),s["default"].createElement("div",{className:n+"-ptr-loading"},r))}}),e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}var r=n(1),o=(i(r),n(9)),a=i(o),s=n(105),l=i(s),u=16,c={scrollResponderMixinGetInitialState:function(){return{isTouching:!1,lastMomentumScrollBeginTime:0,lastMomentumScrollEndTime:0,observedScrollSinceBecomingResponder:!1,becameResponderWhileAnimating:!1}},scrollResponderHandleScrollShouldSetResponder:function(){return this.state.isTouching},scrollResponderHandleStartShouldSetResponder:function(){return!1},scrollResponderHandleStartShouldSetResponderCapture:function(e){return this.scrollResponderIsAnimating()},scrollResponderHandleMoveShouldSetResponderCapture:function(e){return!0},scrollResponderHandleResponderReject:function(){(0,l["default"])(!1,"ScrollView doesn't take rejection well - scrolls anyway")},scrollResponderHandleTerminationRequest:function(){return!this.state.observedScrollSinceBecomingResponder},scrollResponderHandleTouchEnd:function(e){var t=e.nativeEvent;this.state.isTouching=0!==t.touches.length,this.props.onTouchEnd&&this.props.onTouchEnd(e)},scrollResponderHandleResponderRelease:function(e){this.props.onResponderRelease&&this.props.onResponderRelease(e),this.props.keyboardShouldPersistTaps||this.state.observedScrollSinceBecomingResponder||this.state.becameResponderWhileAnimating||this.props.onScrollResponderKeyboardDismissed&&this.props.onScrollResponderKeyboardDismissed(e)},scrollResponderHandleScroll:function(e){this.state.observedScrollSinceBecomingResponder=!0,this.props.onScroll&&this.props.onScroll(e)},scrollResponderHandleResponderGrant:function(e){this.state.observedScrollSinceBecomingResponder=!1,this.props.onResponderGrant&&this.props.onResponderGrant(e),this.state.becameResponderWhileAnimating=this.scrollResponderIsAnimating()},scrollResponderHandleScrollBeginDrag:function(e){this.props.onScrollBeginDrag&&this.props.onScrollBeginDrag(e)},scrollResponderHandleScrollEndDrag:function(e){this.props.onScrollEndDrag&&this.props.onScrollEndDrag(e)},scrollResponderHandleMomentumScrollBegin:function(e){this.state.lastMomentumScrollBeginTime=Date.now(),this.props.onMomentumScrollBegin&&this.props.onMomentumScrollBegin(e)},scrollResponderHandleMomentumScrollEnd:function(e){this.state.lastMomentumScrollEndTime=Date.now(),this.props.onMomentumScrollEnd&&this.props.onMomentumScrollEnd(e)},scrollResponderHandleTouchStart:function(e){this.state.isTouching=!0,this.props.onTouchStart&&this.props.onTouchStart(e)},scrollResponderHandleTouchMove:function(e){this.props.onTouchMove&&this.props.onTouchMove(e)},scrollResponderIsAnimating:function(){var e=Date.now(),t=e-this.state.lastMomentumScrollEndTime,n=t<u||this.state.lastMomentumScrollEndTime<this.state.lastMomentumScrollBeginTime;return n},scrollResponderScrollTo:function(e,t){this.scrollResponderScrollWithouthAnimationTo(e,t)},scrollResponderScrollWithouthAnimationTo:function(e,t){var n=a["default"].findDOMNode(this);n.offsetX=e,n.offsetY=t},scrollResponderZoomTo:function(e){},scrollResponderScrollNativeHandleToKeyboard:function(e,t,n){this.additionalScrollOffset=t||0,this.preventNegativeScrollOffset=!!n},scrollResponderInputMeasureAndScrollToKeyboard:function(e,t,n,i){if(this.keyboardWillOpenTo){var r=t-this.keyboardWillOpenTo.endCoordinates.screenY+i+this.additionalScrollOffset;this.preventNegativeScrollOffset&&(r=Math.max(0,r)),this.scrollResponderScrollTo(0,r)}this.additionalOffset=0,this.preventNegativeScrollOffset=!1},scrollResponderTextInputFocusError:function(e){console.error("Error measuring text field: ",e)},componentWillMount:function(){},scrollResponderKeyboardWillShow:function(e){this.keyboardWillOpenTo=e,this.props.onKeyboardWillShow&&this.props.onKeyboardWillShow(e)},scrollResponderKeyboardWillHide:function(e){this.keyboardWillOpenTo=null,this.props.onKeyboardWillHide&&this.props.onKeyboardWillHide(e)},scrollResponderKeyboardDidShow:function(e){e&&(this.keyboardWillOpenTo=e),this.props.onKeyboardDidShow&&this.props.onKeyboardDidShow(e)},scrollResponderKeyboardDidHide:function(){this.keyboardWillOpenTo=null,this.props.onKeyboardDidHide&&this.props.onKeyboardDidHide()}},d={Mixin:c};e.exports=d},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(6),o=i(r),a=n(2),s=i(a),l=n(4),u=i(l),c=n(3),d=i(c),f=n(1),p=i(f),h=n(9),m=i(h),y=n(119),v=i(y),g=n(10),b=i(g),M=n(5),T=i(M),x=n(73),C="ScrollView",_="InnerScrollView",w={contentContainerStyle:f.PropTypes.object,onScroll:f.PropTypes.func,scrollEventThrottle:f.PropTypes.number,removeClippedSubviews:f.PropTypes.bool,refreshControl:f.PropTypes.element},S={base:{position:"relative",overflow:"auto",WebkitOverflowScrolling:"touch",flex:1},zScroller:{position:"relative",overflow:"hidden",flex:1}},N=function(e){function t(){var n,i,r;(0,s["default"])(this,t);for(var o=arguments.length,a=Array(o),l=0;l<o;l++)a[l]=arguments[l];return n=i=(0,u["default"])(this,e.call.apply(e,[this].concat(a))),i.handleScroll=function(e){i.props.onScroll&&i.props.onScroll(e)},i.throttleScroll=function(){var e=function(){};return i.props.scrollEventThrottle&&i.props.onScroll&&(e=(0,x.throttle)(i.handleScroll,i.props.scrollEventThrottle)),e},r=n,(0,u["default"])(i,r)}return(0,d["default"])(t,e),t.prototype.componentDidUpdate=function(e,t){if(e.refreshControl&&this.props.refreshControl){var n=e.refreshControl.props.refreshing,i=this.props.refreshControl.props.refreshing;n&&!i&&this.refreshControlRefresh?this.refreshControlRefresh():this.manuallyRefresh||n||!i||this.domScroller.scroller.triggerPullToRefresh()}},t.prototype.componentDidMount=function(){var e=this,t=this.props,n=t.stickyHeader,i=t.useBodyScroll,r=t.useZscroller,o=t.scrollerOptions,a=t.refreshControl; if(!n&&!i)return this.tsExec=this.throttleScroll(),r?(this.domScroller=new v["default"](m["default"].findDOMNode(this.refs[_]),(0,b["default"])({},{scrollingX:!1,onScroll:this.tsExec},o)),void(a&&!function(){var t=e.domScroller.scroller,n=a.props,i=n.distanceToRefresh,r=n.onRefresh;t.activatePullToRefresh(i,function(){e.manuallyRefresh=!0,e.refs.refreshControl.setState({active:!0})},function(){e.manuallyRefresh=!1,e.refs.refreshControl.setState({active:!1,loadingState:!1})},function(){e.refs.refreshControl.setState({loadingState:!0});var n=function(){t.finishPullToRefresh(),e.refreshControlRefresh=null};Promise.all([new Promise(function(t){r(),e.refreshControlRefresh=t}),new Promise(function(e){return setTimeout(e,1e3)})]).then(n,n)}),a.props.refreshing&&t.triggerPullToRefresh()}())):void m["default"].findDOMNode(this.refs[C]).addEventListener("scroll",this.tsExec)},t.prototype.componentWillUnmount=function(){var e=this.props,t=e.stickyHeader,n=e.useBodyScroll,i=e.useZscroller;if(!t&&!n)return i?void this.domScroller.destroy():void m["default"].findDOMNode(this.refs[C]).removeEventListener("scroll",this.tsExec)},t.prototype.render=function(){var e,t,n=this.props,i=n.children,r=n.className,a=n.prefixCls,s=void 0===a?"":a,l=n.listPrefixCls,u=void 0===l?"":l,c=n.listViewPrefixCls,d=void 0===c?"rmc-list-view":c,f=n.style,h=void 0===f?{}:f,m=n.contentContainerStyle,y=n.useZscroller,v=n.refreshControl,g=n.stickyHeader,M=n.useBodyScroll,x=S.base;g||M?x=null:y&&(x=S.zScroller);var w=s||d||"",N={ref:C,style:(0,b["default"])({},x,h),className:(0,T["default"])((e={},(0,o["default"])(e,r,!!r),(0,o["default"])(e,w+"-scrollview",!0),e))},E={ref:_,style:(0,b["default"])({},{position:"absolute",minWidth:"100%"},m),className:(0,T["default"])((t={},(0,o["default"])(t,w+"-scrollview-content",!0),(0,o["default"])(t,u,!!u),t))};return v?p["default"].createElement("div",N,p["default"].createElement("div",E,p["default"].cloneElement(v,{ref:"refreshControl"}),i)):g||M?p["default"].createElement("div",N,i):p["default"].createElement("div",N,p["default"].createElement("div",E,i))},t}(p["default"].Component);N.propTypes=w,t["default"]=N,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(2),o=i(r),a=n(4),s=i(a),l=n(3),u=i(l),c=n(1),d=i(c),f=function(e){function t(){return(0,o["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.shouldComponentUpdate=function(e){return e.shouldUpdate},t.prototype.render=function(){return this.props.render()},t}(d["default"].Component);f.propTypes={shouldUpdate:c.PropTypes.bool.isRequired,render:c.PropTypes.func.isRequired},t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function r(){}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=i(o);t["default"]={getDefaultProps:function(){return{onVisibleChange:r,okText:"Ok",dismissText:"Dismiss",title:"",onOk:r,onDismiss:r}},getInitialState:function(){return{visible:this.props.visible||!1}},componentWillReceiveProps:function(e){"visible"in e&&this.setVisibleState(e.visible)},setVisibleState:function(e){this.setState({visible:e})},fireVisibleChange:function(e){this.state.visible!==e&&("visible"in this.props||this.setVisibleState(e),this.props.onVisibleChange(e))},getRender:function(){var e=this.props,t=e.children;if(!t)return this.getModal();var n=this.props,i=n.WrapComponent,r=n.disabled,o=t,s={};return r||(s[e.triggerType]=this.onTriggerClick),a.createElement(i,{style:e.wrapStyle},a.cloneElement(o,s),this.getModal())},onTriggerClick:function(e){var t=this.props.children,n=t.props||{};n[this.props.triggerType]&&n[this.props.triggerType](e),this.fireVisibleChange(!this.state.visible)},onOk:function(){this.props.onOk(),this.fireVisibleChange(!1)},onDismiss:function(){this.props.onDismiss(),this.fireVisibleChange(!1)},hide:function(){this.fireVisibleChange(!1)}},e.exports=t["default"]},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(117);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return i(r)["default"]}}),e.exports=t["default"]},function(e,t){"use strict";function n(e){return!e||!e.length}function i(e,t,i){if(n(e)&&n(t))return!0;if(i)return e===t;if(e.length!==t.length)return!1;for(var r=e.length,o=0;o<r;o++)if(e[o].value!==t[o].value||e[o].label!==t[o].label)return!1;return!0}Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyArray=n,t["default"]=i},function(e,t){function n(e){return Object.prototype.toString.call(e)}function i(e){return e}function r(e){return"function"!=typeof e?e:function(){return e.apply(this,arguments)}}function o(e,t,n){t in e?e[t]=n:Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0})}function a(e,t,i){if(void 0!==e&&void 0!==t){var r=function(e){return e&&e.constructor&&e.constructor.name?e.constructor.name:n(e).slice(8,-1)};throw new TypeError("Cannot mixin key "+i+" because it is provided by multiple sources, and the types are "+r(e)+" and "+r(t))}return void 0===e?t:e}function s(e,t){var i=n(e);if("[object Object]"!==i){var r=e.constructor?e.constructor.name:"Unknown",o=t.constructor?t.constructor.name:"Unknown";throw new Error("cannot merge returned value of type "+r+" with an "+o)}}var l=e.exports=function(e,t){var n=t||{};return n.unknownFunction||(n.unknownFunction=l.ONCE),n.nonFunctionProperty||(n.nonFunctionProperty=a),function(t,i){Object.keys(i).forEach(function(a){var s=t[a],l=i[a],u=e[a];if(void 0!==s||void 0!==l){if(u){var c=u(s,l,a);return void o(t,a,r(c))}var d="function"==typeof s,f="function"==typeof l;return d&&void 0===l||f&&void 0===s||d&&f?void o(t,a,r(n.unknownFunction(s,l,a))):void(t[a]=n.nonFunctionProperty(s,l,a))}})}};l._mergeObjects=function(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);s(e,t),s(t,e);var n={};return Object.keys(e).forEach(function(i){if(Object.prototype.hasOwnProperty.call(t,i))throw new Error("cannot merge returns because both have the "+JSON.stringify(i)+" key");n[i]=e[i]}),Object.keys(t).forEach(function(e){n[e]=t[e]}),n},l.ONCE=function(e,t,n){if(e&&t)throw new TypeError("Cannot mixin "+n+" because it has a unique constraint.");return e||t},l.MANY=function(e,t,n){return function(){return t&&t.apply(this,arguments),e?e.apply(this,arguments):void 0}},l.MANY_MERGED_LOOSE=function(e,t,n){return e&&t?l._mergeObjects(e,t):e||t},l.MANY_MERGED=function(e,t,n){return function(){var n=t&&t.apply(this,arguments),i=e&&e.apply(this,arguments);return n&&i?l._mergeObjects(n,i):i||n}},l.REDUCE_LEFT=function(e,t,n){var r=e||i,o=t||i;return function(){return o.call(this,r.apply(this,arguments))}},l.REDUCE_RIGHT=function(e,t,n){var r=e||i,o=t||i;return function(){return r.call(this,o.apply(this,arguments))}}},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQ0cHgiIGhlaWdodD0iNDRweCIgdmlld0JveD0iMCAwIDQ0IDQ0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0NCA0NCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8Zz4NCgk8cGF0aCBkPSJNMjIuMDI2LDFjLTExLjU5OCwwLTIxLDkuNDAyLTIxLDIxczkuNDAyLDIxLDIxLDIxYzExLjU5OCwwLDIxLTkuNDAyLDIxLTIxUzMzLjYyNCwxLDIyLjAyNiwxeiBNMjIuMDI2LDM5Ljg2NQ0KCQlDMTIuMTYsMzkuODY1LDQuMTYxLDMxLjg2Niw0LjE2MSwyMlMxMi4xNiw0LjEzNSwyMi4wMjYsNC4xMzVjOS44NjYsMCwxNy44NjUsNy45OTgsMTcuODY1LDE3Ljg2NVMzMS44OTIsMzkuODY1LDIyLjAyNiwzOS44NjV6Ig0KCQkvPg0KCTxwb2x5Z29uIHBvaW50cz0iMTguNjI1LDI3LjE4OCAxMiwyMC41IDkuODc1LDIyLjY4OCAxOC44NzUsMzEuNTYyIDM0LjI1LDEzLjQzOCAzMiwxMS41NjIgCSIvPg0KPC9nPg0KPC9zdmc+DQo="},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8yIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQ0cHgiIGhlaWdodD0iNDRweCIgdmlld0JveD0iMCAwIDQ0IDQ0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0NCA0NCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTIxLjkyNiwxLjk1OGMtMTEuMDQ2LDAtMjAsOC45NTQtMjAsMjBjMCwxMS4wNDYsOC45NTQsMjAsMjAsMjANCgljMTEuMDQ2LDAsMjAtOC45NTQsMjAtMjBDNDEuOTI2LDEwLjkxMywzMi45NzIsMS45NTgsMjEuOTI2LDEuOTU4eiBNMzQuMzk2LDE1LjE4OUwyMC4xNTcsMjkuNDI4DQoJYy0wLjU5NCwwLjU5NC0xLjU1OCwwLjU5My0yLjE1My0wLjAwMmMtMC4wNzktMC4wNzktMC4xMTktMC4xNzYtMC4xNzctMC4yNjVjLTAuMDg4LTAuMDU5LTAuMTcyLTAuMTI2LTAuMjUtMC4yMDRsLTcuNDc1LTcuNDc1DQoJYy0wLjY0OS0wLjY0OS0wLjY1NS0xLjY5Ni0wLjAwMi0yLjM0OWMwLjY0OC0wLjY0OCwxLjcwMi0wLjY0NSwyLjM0OSwwLjAwMmw2Ljg0Niw2Ljg0NmwxMi45NDYtMTIuOTQ2DQoJYzAuNTk0LTAuNTk0LDEuNTU4LTAuNTkzLDIuMTUzLDAuMDAyQzM0Ljk5MywxMy42MzUsMzQuOTksMTQuNTk1LDM0LjM5NiwxNS4xODl6Ii8+DQo8L3N2Zz4NCg=="},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDQiIGhlaWdodD0iNDQiIHZpZXdCb3g9IjAgMCA0NCA0NCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+T3BlcmF0aW9uIEljb25zIENvcHkgNjwvdGl0bGU+PHBhdGggZD0iTTM0LjUzOCA4TDM4IDExLjUxOCAxNy44MDggMzIgOCAyMi4wMzNsMy40NjItMy41MTggNi4zNDYgNi40NXoiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvc3ZnPg=="},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTE5NSAxMTk1IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxwYXRoIGQ9Ik02NDMuMzMzIDY0MGwxOTUtMTkxcTktMTAgOS41LTIzdC04LjUtMjNxLTEwLTktMjMtOXQtMjMgOWwtMTk2IDE5Mi0xOTYtMTkycS0xMC05LTIzLTl0LTIzIDEwcS05IDktOSAyMi41dDEwIDIyLjVsMTk1IDE5MS0xOTUgMTkxcS05IDEwLTkuNSAyM3Q4LjUgMjNxMTAgOSAyMyA5dDIzLTlsMTk2LTE5MiAxOTYgMTkycTEwIDkgMjMgOXQyMy0xMHE5LTkgOS0yMi41dC0xMC0yMi41em0tNDYtNDQ4cTkxIDAgMTc0IDM1IDgxIDM0IDE0MyA5NnQ5NiAxNDNxMzUgODMgMzUgMTc0dC0zNSAxNzRxLTM0IDgxLTk2IDE0M3QtMTQzIDk2cS04MyAzNS0xNzQgMzV0LTE3NC0zNXEtODEtMzQtMTQzLTk2dC05Ni0xNDNxLTM1LTgzLTM1LTE3NHQzNS0xNzRxMzQtODEgOTYtMTQzdDE0My05NnE4My0zNSAxNzQtMzV6bTAtNjRxLTEzOSAwLTI1NyA2OC41VDE1My44MzMgMzgzdC02OC41IDI1NyA2OC41IDI1NyAxODYuNSAxODYuNSAyNTcgNjguNSAyNTctNjguNSAxODYuNS0xODYuNSA2OC41LTI1Ny02OC41LTI1Ny0xODYuNS0xODYuNS0yNTctNjguNXoiLz48L3N2Zz4="},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8yIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQ0cHgiIGhlaWdodD0iNDRweCIgdmlld0JveD0iMCAwIDQ0IDQ0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0NCA0NCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTIyLDQyYzExLjA0NiwwLDIwLTguOTU0LDIwLTIwUzMzLjA0NiwyLDIyLDJTMiwxMC45NTQsMiwyMlMxMC45NTQsNDIsMjIsNDJ6DQoJIE0yMi4wNzQsMTkuNjk4bC01LjkxNy01LjkxN2MtMC42NTItMC42NTItMS43MDQtMC42NTMtMi4zNTItMC4wMDVjLTAuNjUzLDAuNjUzLTAuNjQ2LDEuNzAxLDAuMDA1LDIuMzUybDUuOTE3LDUuOTE3bC02LjA2NCw2LjA2NA0KCWMtMC41OTQsMC41OTQtMC41OTcsMS41NTQsMC4wMDIsMi4xNTNjMC41OTUsMC41OTUsMS41NTksMC41OTYsMi4xNTMsMC4wMDJsNi4wNjQtNi4wNjRsNS45NjEsNS45NjENCgljMC42NTIsMC42NTIsMS43MDQsMC42NTMsMi4zNTIsMC4wMDVjMC42NTMtMC42NTMsMC42NDYtMS43MDEtMC4wMDUtMi4zNTJsLTUuOTYxLTUuOTYxbDUuODI4LTUuODI4DQoJYzAuNTk0LTAuNTk0LDAuNTk3LTEuNTU0LTAuMDAyLTIuMTUzYy0wLjU5NS0wLjU5NS0xLjU1OS0wLjU5Ni0yLjE1My0wLjAwMkwyMi4wNzQsMTkuNjk4eiIvPg0KPC9zdmc+DQo="},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDQiIGhlaWdodD0iNDQiIHZpZXdCb3g9IjAgMCA0NCA0NCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+T3BlcmF0aW9uIEljb25zIENvcHkgMThAM3g8L3RpdGxlPjxnIGZpbGwtcnVsZT0iZXZlbm9kZCI+PHBhdGggZD0iTTI5Ljg3IDEwLjc3OGwzLjUzNiAzLjUzNi0xOS4wOTIgMTkuMDkyLTMuNTM2LTMuNTM2eiIvPjxwYXRoIGQ9Ik0zMy40MDYgMjkuODdsLTMuNTM2IDMuNTM2LTE5LjA5Mi0xOS4wOTIgMy41MzYtMy41MzZ6Ii8+PC9nPjwvc3ZnPg=="},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDQiIGhlaWdodD0iNDQiIHZpZXdCb3g9IjAgMCA0NCA0NCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+T3BlcmF0aW9uIEljb25zIENvcHkgNDwvdGl0bGU+PHBhdGggZD0iTTIyLjM1NSAyOC4yMzdsLTExLjQ4My0xMC45Yy0uNjA3LS41NzYtMS43MTQtLjM5Ni0yLjQ4LjQxbC42NzQtLjcxYy0uNzYzLjgwMi0uNzMgMi4wNzEtLjI4MiAyLjQ5NmwxMS4zNyAxMC43OTMtLjA0LjAzOSAyLjA4OCAyLjE5NiAxLjA5OC0xLjA0MyAxMi4zMDgtMTEuNjgyYy40NDctLjQyNS40OC0xLjY5NC0uMjgyLTIuNDk2bC42NzQuNzFjLS43NjYtLjgwNi0xLjg3My0uOTg2LTIuNDgtLjQxTDIyLjM1NSAyOC4yMzd6IiBmaWxsLXJ1bGU9ImV2ZW5vZGQiLz48L3N2Zz4="},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl80IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQ0cHgiIGhlaWdodD0iNDRweCIgdmlld0JveD0iMCAwIDQ0IDQ0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0NCA0NCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8Zz4NCgk8cGF0aCBkPSJNMjIuMTMsMC4xMDljLTEyLjA4MSwwLTIxLjg3NSw5Ljc5NC0yMS44NzUsMjEuODc1czkuNzk0LDIxLjg3NSwyMS44NzUsMjEuODc1czIxLjg3NS05Ljc5NCwyMS44NzUtMjEuODc1DQoJCVMzNC4yMTEsMC4xMDksMjIuMTMsMC4xMDl6IE0yMi4xMywzOS4zMDljLTkuNTY4LDAtMTcuMzI1LTcuNzU3LTE3LjMyNS0xNy4zMjVjMC05LjU2OCw3Ljc1Ny0xNy4zMjUsMTcuMzI1LTE3LjMyNQ0KCQlzMTcuMzI1LDcuNzU3LDE3LjMyNSwxNy4zMjVDMzkuNDU1LDMxLjU1MiwzMS42OTgsMzkuMzA5LDIyLjEzLDM5LjMwOXoiLz4NCgk8Y2lyY2xlIGN4PSIyMS44ODgiIGN5PSIyMS43MDEiIHI9IjIuNDQ1Ii8+DQoJPGNpcmNsZSBjeD0iMTIuMjMiIGN5PSIyMS43MDEiIHI9IjIuNDQ1Ii8+DQoJPGNpcmNsZSBjeD0iMzEuNTQ2IiBjeT0iMjEuNzAxIiByPSIyLjQ0NSIvPg0KPC9nPg0KPC9zdmc+DQo="},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl80IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQ0cHgiIGhlaWdodD0iNDRweCIgdmlld0JveD0iMCAwIDQ0IDQ0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0NCA0NCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8Zz4NCgk8Y2lyY2xlIGN4PSIyMS44ODgiIGN5PSIyMiIgcj0iNC4wNDUiLz4NCgk8Y2lyY2xlIGN4PSI1LjkxMyIgY3k9IjIyIiByPSI0LjA0NSIvPg0KCTxjaXJjbGUgY3g9IjM3Ljg2MyIgY3k9IjIyIiByPSI0LjA0NSIvPg0KPC9nPg0KPC9zdmc+DQo="},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjQiIGhlaWdodD0iNjQiIHZpZXdCb3g9IjAgMCA2NCA2NCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+U2hhcmUgSWNvbnMgQ29weSAzPC90aXRsZT48cGF0aCBkPSJNNTkuNTggNDAuODg5TDQxLjE5MyA5LjExQzM5LjEzNSA1LjM4MiAzNS43MjMgMyAzMS4zODcgM2MtMy4xMSAwLTYuNTIxIDIuMzgyLTguNTggNi4xMTFMNC40MiA0MC44OUMxLjYzMiA0NS41MjUgMS4yOTQgNDkuNyAzLjE5NSA1My4xMSA1LjAxNSA1Ni4yMDggNy41NzIgNTggMTMgNThoMzYuNzczYzUuNDI4IDAgOS4yMS0xLjc5MiAxMS4wMzEtNC44ODkgMS45LTMuNDEgMS41NjQtNy41ODQtMS4yMjUtMTIuMjIyem0tMi40NTIgMTFjLS42MzUgMS42OTUtMy44MDIgMi40NDQtNy4zNTQgMi40NDRIMTNjLTMuNTkxIDAtNS40OTMtLjc1LTYuMTI5LTIuNDQ0LTEuNzEyLTIuNDEtMS4zNzUtNS4yNjIgMC04LjU1NmwxOC4zODYtMzEuNzc3YzIuMTE2LTMuMTY4IDQuMzk0LTQuODkgNi4xMy00Ljg5IDIuOTYgMCA1LjIzOCAxLjcyMiA3LjM1NCA0Ljg5bDE4LjM4NiAzMS43NzdjMS4zNzQgMy4yOTQgMS43MTMgNi4xNDYgMCA4LjU1NnptLTI1Ljc0LTMzYy0uNDA1IDAtMS4yMjcuODM2LTEuMjI3IDIuNDQ0djE1Ljg5YzAgMS42MDguODIyIDIuNDQ0IDEuMjI2IDIuNDQ0IDEuNjI4IDAgMi40NTItLjgzNiAyLjQ1Mi0yLjQ0NVYyMS4zMzNjMC0xLjYwOC0uODI0LTIuNDQ0LTIuNDUyLTIuNDQ0em0wIDIzLjIyMmMtLjQwNSAwLTEuMjI3Ljc4OC0xLjIyNyAxLjIyMnYyLjQ0NWMwIC40MzQuODIyIDEuMjIyIDEuMjI2IDEuMjIyIDEuNjI4IDAgMi40NTItLjc4OCAyLjQ1Mi0xLjIyMnYtMi40NDVjMC0uNDM0LS44MjQtMS4yMjItMi40NTItMS4yMjJ6IiBmaWxsLXJ1bGU9ImV2ZW5vZGQiLz48L3N2Zz4="},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQ0cHgiIGhlaWdodD0iNDRweCIgdmlld0JveD0iMCAwIDQ0IDQ0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0NCA0NCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8Zz4NCgk8Y2lyY2xlIGN4PSIxMy44MjgiIGN5PSIxOS42MyIgcj0iMS45MzgiLz4NCgk8Y2lyY2xlIGN4PSIyMS43NjciIGN5PSIxOS42MyIgcj0iMS45MzgiLz4NCgk8Y2lyY2xlIGN4PSIyOS43NjciIGN5PSIxOS42MyIgcj0iMS45MzgiLz4NCgk8cGF0aCBkPSJNMjIuMTAyLDQuMTYxYy05LjkxOCwwLTE3Ljk1OCw3LjE0Ni0xNy45NTgsMTUuOTYxYzAsNC45MzUsMi41MjIsOS4zNDUsNi40ODEsMTIuMjczdjUuNjY3bDAuMDM4LDAuMDEyDQoJCWMwLjE4MiwxLjI4LDEuMjcyLDIuMjY3LDIuNjAyLDIuMjY3YzAuNzQ3LDAsMS40MTktMC4zMTMsMS44OTktMC44MTJsMC4wMDIsMC4wMDFsNS4wMjYtMy41MzkNCgkJYzAuNjI4LDAuMDU5LDEuMjY1LDAuMDkzLDEuOTExLDAuMDkzYzkuOTE4LDAsMTcuOTU4LTcuMTQ2LDE3Ljk1OC0xNS45NjFDNDAuMDYsMTEuMzA3LDMyLjAyLDQuMTYxLDIyLjEwMiw0LjE2MXogTTIyLjA2MiwzNC4wNjINCgkJYy0wLjkwMiwwLTEuNzgxLTAuMDgxLTIuNjQyLTAuMjA3bC01Ljg4Miw0LjIzNGMtMC4wMjQsMC4wMjUtMC4wNTUsMC4wNC0wLjA4MywwLjA2bC0wLjAwOCwwLjAwNmwwLDANCgkJYy0wLjA4MywwLjA1NS0wLjE3NywwLjA5NS0wLjI4NCwwLjA5NWMtMC4yOSwwLTAuNTI1LTAuMjM1LTAuNTI1LTAuNTI1bDAuMDA1LTYuMzc1Yy0zLjkxLTIuNTE2LTYuNDU2LTYuNTQ0LTYuNDU2LTExLjENCgkJYzAtNy42MjgsNy4xMDctMTMuODEyLDE1Ljg3NS0xMy44MTJzMTUuODc1LDYuMTg0LDE1Ljg3NSwxMy44MTJTMzAuODMsMzQuMDYyLDIyLjA2MiwzNC4wNjJ6Ii8+DQo8L2c+DQo8L3N2Zz4NCg=="},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8yIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQzcHgiIGhlaWdodD0iMzhweCIgdmlld0JveD0iMCAwIDQzIDM4IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0MyAzOCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8Zz4NCgk8cGF0aCBkPSJNMzcuNzUsMC4yMjdINS4yNWMtMy4xMjUsMC00LjU5LDIuNDI1LTQuNTksNC4zMTV2OC4wM2MwLDkuMzQ2LDUuNzUxLDE3LjIxMywxMy42NCwyMC4zNQ0KCQljMC4xMjksMC4wNDksMC4yNDIsMC4xMzUsMC4zMjUsMC4yNDZjMC4xNDUsMC4yMDcsMC4xMjgsMC40MDksMC4xMjgsMC40MDlsMC4wMDEsMi4wMzNjMCwwLDAuMjQxLDAuNzQzLDAuNjY3LDEuMTY3DQoJCWMwLjI1NCwwLjI1NCwwLjg5OSwwLjU0NSwxLjIwMSwwLjU3N2MwLjkyOSwwLjA5OSwyLjA1OSwwLjIyNiw0LjcxNi0wLjEyNWM0Ljg1LTAuNjQ5LDkuNDA2LTIuNzA2LDEzLjExMS01LjkxOA0KCQljNi4xNTctNS4zNDUsOC41NDktMTIuNTQ5LDguNTQ5LTE4LjczOFY0LjYyNUM0Mi45OTgsMi43MzUsNDEuNzkyLDAuMjI3LDM3Ljc1LDAuMjI3eiBNNDEuMDM3LDEzLjI3Mg0KCQljMCw1LjU4LTIuMjc3LDExLjc4NC03Ljg3LDE2LjYwM2MtMy4zNjYsMi44OTYtNy41MTEsNC44MzEtMTEuOTE3LDUuNDE3Yy0yLjQxMywwLjMxNy0zLjM0NywwLjE4Ni00LjE5MSwwLjA5Ng0KCQljLTAuMjc1LTAuMDI5LTAuNDk2LTAuMDc2LTAuMzkyLTEuMDEzYzAuMTA0LTEuOTU4LTAuMTk0LTIuMTU2LTAuMzI1LTIuMzQyYy0wLjA3Ni0wLjEtMC4yNjEtMC4yODctMC4zNzgtMC4zMzINCgkJQzguNzk3LDI4Ljg3NCwyLjU3NywyMS42OTgsMi41NzcsMTMuMjcyVjUuMjAzYzAtMS43MDMsMC4zMzUtMy4wNiwzLjE3My0zLjA2aDMxLjI5MmMzLjY3MSwwLDMuOTk1LDEuMTc0LDMuOTk1LDIuODc4VjEzLjI3MnoiLz4NCgk8cGF0aCBkPSJNMzIuNTMxLDE5LjQ0NGMtMC4zMzYsMC0wLjYyLDAuMTcxLTAuODA5LDAuNDJsLTAuMDEtMC4wMDdsLTAuMDAyLTAuMDAxDQoJCWMtMi4wODMsMy4xMzEtNS42NCw1LjE5Ni05LjY4Miw1LjE5NmMtNi40MTksMC0xMS42MjMtNS4yMDQtMTEuNjIzLTExLjYyM2gtMC4wMzhjLTAuMDItMC41NTItMC40NjctMC45OTUtMS4wMjMtMC45OTUNCgkJYy0wLjU1NiwwLTEuMDAzLDAuNDQzLTEuMDIzLDAuOTk1SDguMzE0YzAsMC4wMSwwLjAwMSwwLjAxOSwwLjAwMSwwLjAyOWMwLDAuMDAzLTAuMDAxLDAuMDA1LTAuMDAxLDAuMDA3DQoJCWMwLDAuMDA0LDAuMDAyLDAuMDA4LDAuMDAyLDAuMDEyYzAuMDI2LDcuNTUyLDYuMTU0LDEzLjY2NywxMy43MTMsMTMuNjY3YzQuNzU3LDAsOC45NDUtMi40MjMsMTEuNDA2LTYuMTAxDQoJCWMwLDAsMC4xMjctMC4zNjgsMC4xMjctMC41N0MzMy41NjEsMTkuOTA1LDMzLjEsMTkuNDQ0LDMyLjUzMSwxOS40NDR6Ii8+DQoJPGVsbGlwc2UgY3g9IjM1LjQ1NiIgY3k9IjEyLjUwNiIgcng9IjEuOTUiIHJ5PSIxLjkxOCIvPg0KPC9nPg0KPC9zdmc+DQo="},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDMiIGhlaWdodD0iMzgiIHZpZXdCb3g9IjAgMCA0MyAzOCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+5Y+j56KRPC90aXRsZT48ZyBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik00LjkyMSAxLjIyN2MtMS44MTQgMC0zLjI4NCAxLjQ1Mi0zLjI4NCAzLjI0M3Y4LjQ1OWMwIDguODYgNi4wNzMgMTYuNTE3IDEzLjU4OSAxOS40OWEuNzAxLjcwMSAwIDAgMSAuMzEuMjMzYy4xMzguMTk2LjEyMi4zODguMTIyLjM4OHYyLjE0OHMtLjAxMi40NjMuMzkzLjg2NWMuMjQyLjI0MS41MDYuMzM4Ljc5NC4zNjguODg1LjA5NCAxLjk2Mi4yMTQgNC40OTMtLjExOWEyMy45NzIgMjMuOTcyIDAgMCAwIDEyLjQ5Mi01LjYxYzUuODY2LTUuMDY3IDguMTQ1LTExLjg5NiA4LjE0NS0xNy43NjNWNC41NjNjMC0xLjc5Mi0xLjQ3LTMuMzM2LTMuMjg1LTMuMzM2SDQuOTJ6IiAvPjxwYXRoIGQ9Ik0zMy41MDYgMTIuNTA2YzAtMS4wNi44NzMtMS45MTggMS45NS0xLjkxOCAxLjA3OCAwIDEuOTUuODU4IDEuOTUgMS45MTggMCAxLjA1OS0uODcyIDEuOTE4LTEuOTUgMS45MTgtMS4wNzcgMC0xLjk1LS44Ni0xLjk1LTEuOTE4eiIgZmlsbD0iI0ZGRiIvPjxwYXRoIGQ9Ik05LjEyNyAxMy40NjVjMCA2LjA4NyA1LjU2NCAxMi44NDcgMTIuNjI2IDEyLjc4NCAzLjMzNi0uMDMgOC4wMDYtMS41MjIgMTAuNzc4LTUuNzg0IiBzdHJva2U9IiNGRkYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PC9nPjwvc3ZnPg=="},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQ0cHgiIGhlaWdodD0iNDRweCIgdmlld0JveD0iMCAwIDQ0IDQ0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0NCA0NCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8dGl0bGU+T3BlcmF0aW9uIEljb25zIENvcHkgNDwvdGl0bGU+DQo8Zz4NCgk8ZGVmcz4NCgkJPHJlY3QgaWQ9IlNWR0lEXzFfIiB4PSItMTI5IiB5PSItODQ1IiB3aWR0aD0iMjQiIGhlaWdodD0iMjQiLz4NCgk8L2RlZnM+DQoJPGNsaXBQYXRoIGlkPSJTVkdJRF8yXyI+DQoJCTx1c2UgeGxpbms6aHJlZj0iI1NWR0lEXzFfIiAgb3ZlcmZsb3c9InZpc2libGUiLz4NCgk8L2NsaXBQYXRoPg0KCTxnIGNsaXAtcGF0aD0idXJsKCNTVkdJRF8yXykiPg0KCQk8ZGVmcz4NCgkJCTxyZWN0IGlkPSJTVkdJRF8zXyIgeD0iLTkwMyIgeT0iLTk0OSIgd2lkdGg9IjE4NTAiIGhlaWdodD0iMTk0NSIvPg0KCQk8L2RlZnM+DQoJCTxjbGlwUGF0aCBpZD0iU1ZHSURfNF8iPg0KCQkJPHVzZSB4bGluazpocmVmPSIjU1ZHSURfM18iICBvdmVyZmxvdz0idmlzaWJsZSIvPg0KCQk8L2NsaXBQYXRoPg0KCQk8cmVjdCB4PSItMTM0IiB5PSItODUwIiBvcGFjaXR5PSIwIiBjbGlwLXBhdGg9InVybCgjU1ZHSURfNF8pIiBmaWxsPSIjRDhEOEQ4IiB3aWR0aD0iMzQiIGhlaWdodD0iMzQiLz4NCgk8L2c+DQo8L2c+DQo8cG9seWdvbiBwb2ludHM9IjE2LjI0NywyMS4zOTkgMjguNDgsOS4xNjYgMzAuNjAxLDExLjI4NyAyMC40ODMsMjEuNDA2IDMwLjYwMSwzMS41MjQgMjguNDgsMzMuNjQ1IDE2LjI0NywyMS40MTIgMTYuMjU0LDIxLjQwNiANCgkiLz4NCjwvc3ZnPg0K"},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQ0cHgiIGhlaWdodD0iNDRweCIgdmlld0JveD0iMCAwIDQ0IDQ0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0NCA0NCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8cGF0aCBkPSJNMjIsMkMxMC45NTQsMiwyLDEwLjk1NCwyLDIyczguOTU0LDIwLDIwLDIwczIwLTguOTU0LDIwLTIwUzMzLjA0NiwyLDIyLDJ6IE0yOSwzMi4zMjNsLTE0Ljk2NCwwLjA4Ng0KCWMtMi4yMTgsMC4wMTItMi43OC0xLjI4NS0xLjI3NS0yLjg5OGMwLDAsMy45MzQtNC4yNDksNi4zNC02LjY1NWMwLjI2OC0wLjI2OCwwLjM5Mi0wLjc0MywwLjQ1LTEuMTExDQoJYy0wLjA1OC0wLjM2OC0wLjE4Mi0wLjg0Mi0wLjQ1LTEuMTExYy0yLjQwNi0yLjQwNS02LjM0LTYuNjU1LTYuMzQtNi42NTVjLTEuNTA1LTEuNjEzLTAuOTQzLTIuOTEsMS4yNzUtMi44OTdMMjksMTEuMTY4DQoJYzIuMjA5LDAuMDEzLDIuNzg0LDEuMzI0LDEuMjY0LDIuOTQ0YzAsMC0zLjg5OCw0LjE5My02LjI4Niw2LjU4MWMtMC4xNywwLjE3LTAuMjU4LDAuNjYtMC4zMDIsMS4wNTINCgljMC4wNDQsMC4zOTMsMC4xMzIsMC44ODMsMC4zMDIsMS4wNTNjMi4zODgsMi4zODgsNi4yODYsNi41ODEsNi4yODYsNi41ODFDMzEuNzg0LDMwLjk5OCwzMS4yMSwzMi4zMSwyOSwzMi4zMjN6Ii8+DQo8L3N2Zz4NCg=="},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDQiIGhlaWdodD0iNDQiIHZpZXdCb3g9IjAgMCA0NCA0NCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+UG9wIGRvd24gbWVudSBJY29ucyBDb3B5IDg8L3RpdGxlPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDIgMikiICBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxjaXJjbGUgY3g9IjIwIiBjeT0iMjAiIHI9IjIwIi8+PHBhdGggZD0iTTIxLjY3NiAxOS43NDVjLjA0NC0uMzkyLjEzMi0uODgyLjMwMi0xLjA1MiAyLjM4OC0yLjM4OCA2LjI4Ni02LjU4MSA2LjI4Ni02LjU4MSAxLjUyLTEuNjIuOTQ1LTIuOTMxLTEuMjY0LTIuOTQ0bC0xNC45NjQtLjA4NmMtMi4yMTgtLjAxMy0yLjc4IDEuMjg0LTEuMjc1IDIuODk3IDAgMCAzLjkzNCA0LjI1IDYuMzQgNi42NTUuMjY4LjI2OS4zOTIuNzQzLjQ1IDEuMTExLS4wNTguMzY4LS4xODIuODQzLS40NSAxLjExMS0yLjQwNiAyLjQwNi02LjM0IDYuNjU1LTYuMzQgNi42NTUtMS41MDUgMS42MTMtLjk0MyAyLjkxIDEuMjc1IDIuODk4TDI3IDMwLjMyM2MyLjIxLS4wMTMgMi43ODQtMS4zMjUgMS4yNjQtMi45NDQgMCAwLTMuODk4LTQuMTkzLTYuMjg2LTYuNTgxLS4xNy0uMTctLjI1OC0uNjYtLjMwMi0xLjA1M3oiIGZpbGw9IiNGRkYiLz48cGF0aCBkPSJNMjEuNTQ4IDIzLjUxOEwyMC4xMyAyMi4xbC42NzIuNjcyYy0uMzkyLS4zOTItMS4xNTctLjcyNi0xLjcxMi0uNzQ2bC41MzkuMDJjLS41NTQtLjAyLTEuMzIuMjgtMS43MDguNjY3bC42LS41OThjLS4zODkuMzg4LTEuMDIgMS4wMjItMS40MDIgMS40MTZsLTQuMTgzIDQuNDM2Yy0uMzc2LjQwNC0uMjMyLjczLjMxMi43M2wxMi40NTQtLjAzYy41NDgtLjAwMi42NzItLjMyMy4yODgtLjcwN2wtNC40NDMtNC40NDN6IiAvPjwvZz48L3N2Zz4="},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDQiIGhlaWdodD0iNDQiIHZpZXdCb3g9IjAgMCA0NCA0NCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+T3BlcmF0aW9uIEljb25zIENvcHkgMTI8L3RpdGxlPjxnIGZpbGwtcnVsZT0iZXZlbm9kZCI+PHBhdGggZD0iTTIxLjE4NiAzQzEwLjMzMyAzIDEuODI3IDExLjUwNiAxLjgyNyAyMi4zNTggMS44MjcgMzIuNDk0IDEwLjMzMyA0MSAyMS4xODYgNDFjMTAuMTMzIDAgMTguNjQxLTguNTA2IDE4LjY0MS0xOC42NDJDMzkuODI3IDExLjUwNiAzMS4zMiAzIDIxLjE4NiAzbTE1LjY0MSAxOWMwIDguODIzLTcuMTc5IDE2LTE2IDE2LTguODIzIDAtMTYtNy4xNzctMTYtMTZzNy4xNzctMTYgMTYtMTZjOC44MjEgMCAxNiA3LjE3NyAxNiAxNnoiLz48cGF0aCBkPSJNMjIuODI3IDMxLjVhMS41IDEuNSAwIDEgMS0yLjk5OS4wMDEgMS41IDEuNSAwIDAgMSAzLS4wMDEiLz48cGF0aCBkPSJNMjYuODI3IDE2LjAyYzAgLjk1Ny0uMjAzIDEuODIyLS42MSAyLjU5My0uNDI3Ljc5Mi0xLjExNyAxLjYxMi0yLjA3MyAyLjQ1Ny0uODY3LjczNC0xLjQ1MyAxLjQzNS0xLjc1NCAyLjA5Ni0uMzAyLjctLjQ1MyAxLjY5My0uNDUzIDIuOTc5YS44MjguODI4IDAgMCAxLS44MjMuODU1LjgyOC44MjggMCAwIDEtLjU4NC0uMjIuODc3Ljg3NyAwIDAgMS0uMjQtLjYzNWMwLTEuMzA1LjE2OC0yLjM4LjUwNi0zLjIyNy4zMzYtLjg4My45My0xLjY4MiAxLjc3OS0yLjQgMS4wMS0uODgzIDEuNzEtMS42OTIgMi4xLTIuNDI4LjMzNy0uNjQ1LjUwNC0xLjM4LjUwNC0yLjIwOS0uMDE4LS45MzYtLjMtMS43LS44NS0yLjI4OS0uNjU0LS43MTctMS42Mi0xLjA3NS0yLjg5Ni0xLjA3NS0xLjUwNiAwLTIuNTk2LjUzNS0zLjI2OSAxLjYtLjQ2Ljc1NC0uNjg5IDEuNjQ1LS42ODkgMi42NzcgMCAuMjU3LS4wOS40NzctLjI2Ni42NmEuNzQ3Ljc0NyAwIDAgMS0uNTU4LjI1LjczLjczIDAgMCAxLS41ODUtLjE5NGMtLjE2LS4xNjQtLjIzOS0uMzkzLS4yMzktLjY5IDAtMS44MTkuNTg0LTMuMjcyIDEuNzU0LTQuMzU3QzE4LjY0NCAxMS40ODYgMTkuOTI3IDExIDIxLjQzMyAxMWguMjkzYzEuNDUyIDAgMi42MzguNDE0IDMuNTYxIDEuMjQxIDEuMDI3LjkwMiAxLjU0IDIuMTYyIDEuNTQgMy43OHoiIC8+PC9nPjwvc3ZnPg=="},function(e,t){e.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNy4wLjIsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IuWbvuWxgl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCINCgkgd2lkdGg9IjQ0cHgiIGhlaWdodD0iNDRweCIgdmlld0JveD0iMCAwIDQ0IDQ0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA0NCA0NCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8dGl0bGU+T3BlcmF0aW9uIEljb25zIENvcHkgNDwvdGl0bGU+DQo8Zz4NCgk8ZGVmcz4NCgkJPHJlY3QgaWQ9IlNWR0lEXzFfIiB4PSItMTI5IiB5PSItODQ1IiB3aWR0aD0iMjQiIGhlaWdodD0iMjQiLz4NCgk8L2RlZnM+DQoJPGNsaXBQYXRoIGlkPSJTVkdJRF8yXyI+DQoJCTx1c2UgeGxpbms6aHJlZj0iI1NWR0lEXzFfIiAgb3ZlcmZsb3c9InZpc2libGUiLz4NCgk8L2NsaXBQYXRoPg0KCTxnIGNsaXAtcGF0aD0idXJsKCNTVkdJRF8yXykiPg0KCQk8ZGVmcz4NCgkJCTxyZWN0IGlkPSJTVkdJRF8zXyIgeD0iLTkwMyIgeT0iLTk0OSIgd2lkdGg9IjE4NTAiIGhlaWdodD0iMTk0NSIvPg0KCQk8L2RlZnM+DQoJCTxjbGlwUGF0aCBpZD0iU1ZHSURfNF8iPg0KCQkJPHVzZSB4bGluazpocmVmPSIjU1ZHSURfM18iICBvdmVyZmxvdz0idmlzaWJsZSIvPg0KCQk8L2NsaXBQYXRoPg0KCQk8cmVjdCB4PSItMTM0IiB5PSItODUwIiBvcGFjaXR5PSIwIiBjbGlwLXBhdGg9InVybCgjU1ZHSURfNF8pIiBmaWxsPSIjRDhEOEQ4IiB3aWR0aD0iMzQiIGhlaWdodD0iMzQiLz4NCgk8L2c+DQo8L2c+DQo8cG9seWdvbiBwb2ludHM9IjMwLjYwMSwyMS4zOTkgMTguMzY4LDkuMTY2IDE2LjI0NywxMS4yODcgMjYuMzY1LDIxLjQwNiAxNi4yNDcsMzEuNTI0IDE4LjM2OCwzMy42NDUgMzAuNjAxLDIxLjQxMiAzMC41OTUsMjEuNDA2IA0KCSIvPg0KPC9zdmc+DQo="},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDQiIGhlaWdodD0iNDQiIHZpZXdCb3g9IjAgMCA0NCA0NCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+U3lzdGVtIEljb25zIENvcHkgODwvdGl0bGU+PHBhdGggZD0iTTMyLjk4MSAyOS4yNTVsOC45MTQgOC4yOTNMMzkuNjAzIDQwbC04Ljg1OS04LjI0MmExNS45NTIgMTUuOTUyIDAgMCAxLTEwLjc1NCA0LjE0N0MxMS4xNiAzNS45MDUgNCAyOC43NjMgNCAxOS45NTIgNCAxMS4xNDIgMTEuMTYgNCAxOS45OSA0czE1Ljk5IDcuMTQyIDE1Ljk5IDE1Ljk1MmMwIDMuNDcyLTEuMTEyIDYuNjg1LTIuOTk5IDkuMzAzem0uMDUtOS4yMWMwIDcuMTIzLTUuNzAxIDEyLjkxOC0xMi44OCAxMi45MTgtNy4xNzcgMC0xMy4wMTYtNS43OTUtMTMuMDE2LTEyLjkxOCAwLTcuMTIgNS44MzktMTIuOTE3IDEzLjAxNy0xMi45MTcgNy4xNzggMCAxMi44NzkgNS43OTcgMTIuODc5IDEyLjkxN3oiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvc3ZnPg=="},function(e,t,n){"use strict";var i=function(){};e.exports=i},function(e,t){(function(t){var n=60,i=1e3,r={},o=1,a="undefined"!=typeof window?window:void 0;a||(a="undefined"!=typeof t?t:{});var s={requestAnimationFrame:function(){var e=a.requestAnimationFrame||a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame,t=!!e;if(e&&!/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(e.toString())&&(t=!1),t)return function(t,n){e(t,n)};var n=60,i={},r=0,o=1,s=null,l=+new Date;return function(e,t){var a=o++;return i[a]=e,r++,null===s&&(s=setInterval(function(){var e=+new Date,t=i;i={},r=0;for(var n in t)t.hasOwnProperty(n)&&(t[n](e),l=e);e-l>2500&&(clearInterval(s),s=null)},1e3/n)),a}}(),stop:function(e){var t=null!=r[e];return t&&(r[e]=null),t},isRunning:function(e){return null!=r[e]},start:function(e,t,a,l,u,c){var d=+new Date,f=d,p=0,h=0,m=o++;if(c||(c=document.body),m%20===0){var y={};for(var v in r)y[v]=!0;r=y}var g=function(o){var y=o!==!0,v=+new Date;if(!r[m]||t&&!t(m))return r[m]=null,void(a&&a(n-h/((v-d)/i),m,!1));if(y)for(var b=Math.round((v-f)/(i/n))-1,M=0;M<Math.min(b,4);M++)g(!0),h++;l&&(p=(v-d)/l,p>1&&(p=1));var T=u?u(p):p;e(T,v,y)!==!1&&1!==p||!y?y&&(f=v,s.requestAnimationFrame(g,c)):(r[m]=null,a&&a(n-h/((v-d)/i),m,1===p||null==l))};return r[m]=!0,s.requestAnimationFrame(g,c),m}};e.exports=s}).call(t,function(){return this}())},function(e,t,n){var i,r=n(449),o=function(){};i=function(e,t){this.__callback=e,this.options={scrollingX:!0,scrollingY:!0,animating:!0,animationDuration:250,bouncing:!0,locking:!0,paging:!1,snapping:!1,zooming:!1,minZoom:.5,maxZoom:3,speedMultiplier:1,scrollingComplete:o,penetrationDeceleration:.03, penetrationAcceleration:.08};for(var n in t)this.options[n]=t[n]};var a=function(e){return Math.pow(e-1,3)+1},s=function(e){return(e/=.5)<1?.5*Math.pow(e,3):.5*(Math.pow(e-2,3)+2)},l={__isSingleTouch:!1,__isTracking:!1,__didDecelerationComplete:!1,__isGesturing:!1,__isDragging:!1,__isDecelerating:!1,__isAnimating:!1,__clientLeft:0,__clientTop:0,__clientWidth:0,__clientHeight:0,__contentWidth:0,__contentHeight:0,__snapWidth:100,__snapHeight:100,__refreshHeight:null,__refreshActive:!1,__refreshActivate:null,__refreshDeactivate:null,__refreshStart:null,__zoomLevel:1,__scrollLeft:0,__scrollTop:0,__maxScrollLeft:0,__maxScrollTop:0,__scheduledLeft:0,__scheduledTop:0,__scheduledZoom:0,__lastTouchLeft:null,__lastTouchTop:null,__lastTouchMove:null,__positions:null,__minDecelerationScrollLeft:null,__minDecelerationScrollTop:null,__maxDecelerationScrollLeft:null,__maxDecelerationScrollTop:null,__decelerationVelocityX:null,__decelerationVelocityY:null,setDimensions:function(e,t,n,i){var r=this;e===+e&&(r.__clientWidth=e),t===+t&&(r.__clientHeight=t),n===+n&&(r.__contentWidth=n),i===+i&&(r.__contentHeight=i),r.__computeScrollMax(),r.scrollTo(r.__scrollLeft,r.__scrollTop,!0)},setPosition:function(e,t){var n=this;n.__clientLeft=e||0,n.__clientTop=t||0},setSnapSize:function(e,t){var n=this;n.__snapWidth=e,n.__snapHeight=t},activatePullToRefresh:function(e,t,n,i){var r=this;r.__refreshHeight=e,r.__refreshActivate=t,r.__refreshDeactivate=n,r.__refreshStart=i},triggerPullToRefresh:function(){this.__publish(this.__scrollLeft,-this.__refreshHeight,this.__zoomLevel,!0),this.__refreshStart&&this.__refreshStart()},finishPullToRefresh:function(){var e=this;e.__refreshActive=!1,e.__refreshDeactivate&&e.__refreshDeactivate(),e.scrollTo(e.__scrollLeft,e.__scrollTop,!0)},getValues:function(){var e=this;return{left:e.__scrollLeft,top:e.__scrollTop,zoom:e.__zoomLevel}},getScrollMax:function(){var e=this;return{left:e.__maxScrollLeft,top:e.__maxScrollTop}},zoomTo:function(e,t,n,i,o){var a=this;if(!a.options.zooming)throw new Error("Zooming is not enabled!");o&&(a.__zoomComplete=o),a.__isDecelerating&&(r.stop(a.__isDecelerating),a.__isDecelerating=!1);var s=a.__zoomLevel;null==n&&(n=a.__clientWidth/2),null==i&&(i=a.__clientHeight/2),e=Math.max(Math.min(e,a.options.maxZoom),a.options.minZoom),a.__computeScrollMax(e);var l=(n+a.__scrollLeft)*e/s-n,u=(i+a.__scrollTop)*e/s-i;l>a.__maxScrollLeft?l=a.__maxScrollLeft:l<0&&(l=0),u>a.__maxScrollTop?u=a.__maxScrollTop:u<0&&(u=0),a.__publish(l,u,e,t)},zoomBy:function(e,t,n,i,r){var o=this;o.zoomTo(o.__zoomLevel*e,t,n,i,r)},scrollTo:function(e,t,n,i,o){var a=this;if(a.__isDecelerating&&(r.stop(a.__isDecelerating),a.__isDecelerating=!1),null!=i&&i!==a.__zoomLevel){if(!a.options.zooming)throw new Error("Zooming is not enabled!");e*=i,t*=i,a.__computeScrollMax(i)}else i=a.__zoomLevel;a.options.scrollingX?a.options.paging?e=Math.round(e/a.__clientWidth)*a.__clientWidth:a.options.snapping&&(e=Math.round(e/a.__snapWidth)*a.__snapWidth):e=a.__scrollLeft,a.options.scrollingY?a.options.paging?t=Math.round(t/a.__clientHeight)*a.__clientHeight:a.options.snapping&&(t=Math.round(t/a.__snapHeight)*a.__snapHeight):t=a.__scrollTop,e=Math.max(Math.min(a.__maxScrollLeft,e),0),t=Math.max(Math.min(a.__maxScrollTop,t),0),e===a.__scrollLeft&&t===a.__scrollTop&&(n=!1,o&&o()),a.__isTracking||a.__publish(e,t,i,n)},scrollBy:function(e,t,n){var i=this,r=i.__isAnimating?i.__scheduledLeft:i.__scrollLeft,o=i.__isAnimating?i.__scheduledTop:i.__scrollTop;i.scrollTo(r+(e||0),o+(t||0),n)},doMouseZoom:function(e,t,n,i){var r=this,o=e>0?.97:1.03;return r.zoomTo(r.__zoomLevel*o,!1,n-r.__clientLeft,i-r.__clientTop)},doTouchStart:function(e,t){if(null==e.length)throw new Error("Invalid touch list: "+e);if(t instanceof Date&&(t=t.valueOf()),"number"!=typeof t)throw new Error("Invalid timestamp value: "+t);var n=this;n.__interruptedAnimation=!0,n.__isDecelerating&&(r.stop(n.__isDecelerating),n.__isDecelerating=!1,n.__interruptedAnimation=!0),n.__isAnimating&&(r.stop(n.__isAnimating),n.__isAnimating=!1,n.__interruptedAnimation=!0);var i,o,a=1===e.length;a?(i=e[0].pageX,o=e[0].pageY):(i=Math.abs(e[0].pageX+e[1].pageX)/2,o=Math.abs(e[0].pageY+e[1].pageY)/2),n.__initialTouchLeft=i,n.__initialTouchTop=o,n.__zoomLevelStart=n.__zoomLevel,n.__lastTouchLeft=i,n.__lastTouchTop=o,n.__lastTouchMove=t,n.__lastScale=1,n.__enableScrollX=!a&&n.options.scrollingX,n.__enableScrollY=!a&&n.options.scrollingY,n.__isTracking=!0,n.__didDecelerationComplete=!1,n.__isDragging=!a,n.__isSingleTouch=a,n.__positions=[]},doTouchMove:function(e,t,n){if(null==e.length)throw new Error("Invalid touch list: "+e);if(t instanceof Date&&(t=t.valueOf()),"number"!=typeof t)throw new Error("Invalid timestamp value: "+t);var i=this;if(i.__isTracking){var r,o;2===e.length?(r=Math.abs(e[0].pageX+e[1].pageX)/2,o=Math.abs(e[0].pageY+e[1].pageY)/2):(r=e[0].pageX,o=e[0].pageY);var a=i.__positions;if(i.__isDragging){var s=r-i.__lastTouchLeft,l=o-i.__lastTouchTop,u=i.__scrollLeft,c=i.__scrollTop,d=i.__zoomLevel;if(null!=n&&i.options.zooming){var f=d;if(d=d/i.__lastScale*n,d=Math.max(Math.min(d,i.options.maxZoom),i.options.minZoom),f!==d){var p=r-i.__clientLeft,h=o-i.__clientTop;u=(p+u)*d/f-p,c=(h+c)*d/f-h,i.__computeScrollMax(d)}}if(i.__enableScrollX){u-=s*this.options.speedMultiplier;var m=i.__maxScrollLeft;(u>m||u<0)&&(i.options.bouncing?u+=s/2*this.options.speedMultiplier:u=u>m?m:0)}if(i.__enableScrollY){c-=l*this.options.speedMultiplier;var y=i.__maxScrollTop;(c>y||c<0)&&(i.options.bouncing?(c+=l/2*this.options.speedMultiplier,i.__enableScrollX||null==i.__refreshHeight||(!i.__refreshActive&&c<=-i.__refreshHeight?(i.__refreshActive=!0,i.__refreshActivate&&i.__refreshActivate()):i.__refreshActive&&c>-i.__refreshHeight&&(i.__refreshActive=!1,i.__refreshDeactivate&&i.__refreshDeactivate()))):c=c>y?y:0)}a.length>60&&a.splice(0,30),a.push(u,c,t),i.__publish(u,c,d)}else{var v=i.options.locking?3:0,g=5,b=Math.abs(r-i.__initialTouchLeft),M=Math.abs(o-i.__initialTouchTop);i.__enableScrollX=i.options.scrollingX&&b>=v,i.__enableScrollY=i.options.scrollingY&&M>=v,a.push(i.__scrollLeft,i.__scrollTop,t),i.__isDragging=(i.__enableScrollX||i.__enableScrollY)&&(b>=g||M>=g),i.__isDragging&&(i.__interruptedAnimation=!1)}i.__lastTouchLeft=r,i.__lastTouchTop=o,i.__lastTouchMove=t,i.__lastScale=n}},doTouchEnd:function(e){if(e instanceof Date&&(e=e.valueOf()),"number"!=typeof e)throw new Error("Invalid timestamp value: "+e);var t=this;if(t.__isTracking){if(t.__isTracking=!1,t.__isDragging)if(t.__isDragging=!1,t.__isSingleTouch&&t.options.animating&&e-t.__lastTouchMove<=100){for(var n=t.__positions,i=n.length-1,r=i,o=i;o>0&&n[o]>t.__lastTouchMove-100;o-=3)r=o;if(r!==i){var a=n[i]-n[r],s=t.__scrollLeft-n[r-2],l=t.__scrollTop-n[r-1];t.__decelerationVelocityX=s/a*(1e3/60),t.__decelerationVelocityY=l/a*(1e3/60);var u=t.options.paging||t.options.snapping?4:1;Math.abs(t.__decelerationVelocityX)>u||Math.abs(t.__decelerationVelocityY)>u?t.__refreshActive||t.__startDeceleration(e):t.options.scrollingComplete()}else t.options.scrollingComplete()}else e-t.__lastTouchMove>100&&t.options.scrollingComplete();t.__isDecelerating||(t.__refreshActive&&t.__refreshStart?(t.__publish(t.__scrollLeft,-t.__refreshHeight,t.__zoomLevel,!0),t.__refreshStart&&t.__refreshStart()):((t.__interruptedAnimation||t.__isDragging)&&t.options.scrollingComplete(),t.scrollTo(t.__scrollLeft,t.__scrollTop,!0,t.__zoomLevel),t.__refreshActive&&(t.__refreshActive=!1,t.__refreshDeactivate&&t.__refreshDeactivate()))),t.__positions.length=0}},__publish:function(e,t,n,i){var o=this,l=o.__isAnimating;if(l&&(r.stop(l),o.__isAnimating=!1),i&&o.options.animating){o.__scheduledLeft=e,o.__scheduledTop=t,o.__scheduledZoom=n;var u=o.__scrollLeft,c=o.__scrollTop,d=o.__zoomLevel,f=e-u,p=t-c,h=n-d,m=function(e,t,n){n&&(o.__scrollLeft=u+f*e,o.__scrollTop=c+p*e,o.__zoomLevel=d+h*e,o.__callback&&o.__callback(o.__scrollLeft,o.__scrollTop,o.__zoomLevel))},y=function(e){return o.__isAnimating===e},v=function(e,t,n){t===o.__isAnimating&&(o.__isAnimating=!1),(o.__didDecelerationComplete||n)&&o.options.scrollingComplete(),o.options.zooming&&(o.__computeScrollMax(),o.__zoomComplete&&(o.__zoomComplete(),o.__zoomComplete=null))};o.__isAnimating=r.start(m,y,v,o.options.animationDuration,l?a:s)}else o.__scheduledLeft=o.__scrollLeft=e,o.__scheduledTop=o.__scrollTop=t,o.__scheduledZoom=o.__zoomLevel=n,o.__callback&&o.__callback(e,t,n),o.options.zooming&&(o.__computeScrollMax(),o.__zoomComplete&&(o.__zoomComplete(),o.__zoomComplete=null))},__computeScrollMax:function(e){var t=this;null==e&&(e=t.__zoomLevel),t.__maxScrollLeft=Math.max(t.__contentWidth*e-t.__clientWidth,0),t.__maxScrollTop=Math.max(t.__contentHeight*e-t.__clientHeight,0)},__startDeceleration:function(e){var t=this;if(t.options.paging){var n=Math.max(Math.min(t.__scrollLeft,t.__maxScrollLeft),0),i=Math.max(Math.min(t.__scrollTop,t.__maxScrollTop),0),o=t.__clientWidth,a=t.__clientHeight;t.__minDecelerationScrollLeft=Math.floor(n/o)*o,t.__minDecelerationScrollTop=Math.floor(i/a)*a,t.__maxDecelerationScrollLeft=Math.ceil(n/o)*o,t.__maxDecelerationScrollTop=Math.ceil(i/a)*a}else t.__minDecelerationScrollLeft=0,t.__minDecelerationScrollTop=0,t.__maxDecelerationScrollLeft=t.__maxScrollLeft,t.__maxDecelerationScrollTop=t.__maxScrollTop;var s=function(e,n,i){t.__stepThroughDeceleration(i)},l=t.options.minVelocityToKeepDecelerating;l||(l=t.options.snapping?4:.001);var u=function(){var e=Math.abs(t.__decelerationVelocityX)>=l||Math.abs(t.__decelerationVelocityY)>=l;return e||(t.__didDecelerationComplete=!0),e},c=function(e,n,i){t.__isDecelerating=!1,t.scrollTo(t.__scrollLeft,t.__scrollTop,t.options.snapping,null,t.__didDecelerationComplete&&t.options.scrollingComplete)};t.__isDecelerating=r.start(s,u,c)},__stepThroughDeceleration:function(e){var t=this,n=t.__scrollLeft+t.__decelerationVelocityX,i=t.__scrollTop+t.__decelerationVelocityY;if(!t.options.bouncing){var r=Math.max(Math.min(t.__maxDecelerationScrollLeft,n),t.__minDecelerationScrollLeft);r!==n&&(n=r,t.__decelerationVelocityX=0);var o=Math.max(Math.min(t.__maxDecelerationScrollTop,i),t.__minDecelerationScrollTop);o!==i&&(i=o,t.__decelerationVelocityY=0)}if(e?t.__publish(n,i,t.__zoomLevel):(t.__scrollLeft=n,t.__scrollTop=i),!t.options.paging){var a=.95;t.__decelerationVelocityX*=a,t.__decelerationVelocityY*=a}if(t.options.bouncing){var s=0,l=0,u=t.options.penetrationDeceleration,c=t.options.penetrationAcceleration;n<t.__minDecelerationScrollLeft?s=t.__minDecelerationScrollLeft-n:n>t.__maxDecelerationScrollLeft&&(s=t.__maxDecelerationScrollLeft-n),i<t.__minDecelerationScrollTop?l=t.__minDecelerationScrollTop-i:i>t.__maxDecelerationScrollTop&&(l=t.__maxDecelerationScrollTop-i),0!==s&&(s*t.__decelerationVelocityX<=0?t.__decelerationVelocityX+=s*u:t.__decelerationVelocityX=s*c),0!==l&&(l*t.__decelerationVelocityY<=0?t.__decelerationVelocityY+=l*u:t.__decelerationVelocityY=l*c)}}};for(var u in l)i.prototype[u]=l[u];e.exports=i},function(e,t,n,i){"use strict";n(8),n(i)},function(e,t,n,i){"use strict";n(8),n(16),n(i)},function(e,t,n,i){"use strict";n(8),n(20),n(i)}]))}); //# sourceMappingURL=antd-mobile.min.js.map
src/containers/CampView/About.js
JamesJin038801/CampID
import { Text, View, Platform, Image, ScrollView } from 'react-native'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import I18n from 'react-native-i18n'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import NavigationBar from 'react-native-navbar'; import { setHomeTab } from '@actions/globals'; import { openDrawer } from '@actions/drawer'; import { replaceRoute } from '@actions/route'; import Constants from '@src/constants'; import { Metrics, Styles, Colors, Fonts, Icon } from '@theme/'; import styles from './styles'; import CommonWidgets from '@components/CommonWidgets'; import InfoView from '@components/CampViewItem/InfoView'; import VideoView from '@components/CampViewItem/VideoView'; import AboutCell from '@components/CampViewItem/AboutCell'; import ScrollableTabView, { DefaultTabBar } from 'react-native-scrollable-tab-view'; class About extends Component { render() { return ( <View style={styles.container}> <Text style={Fonts.style.h4}>Work with some of the top basketball coaches in the world. They are ready for you!</Text> {CommonWidgets.renderSpacer(30)} <Text style={Fonts.style.h3}>Camp Instructors</Text> <ScrollView> <AboutCell key={0} /> <AboutCell key={1} /> <AboutCell key={2} /> </ScrollView> </View> ); } } About.propTypes = { dispatch: React.PropTypes.func.isRequired, setHomeTab: React.PropTypes.func.isRequired, replaceRoute: React.PropTypes.func.isRequired, openDrawer: React.PropTypes.func.isRequired, }; function mapDispatchToProps(dispatch) { return { dispatch, setHomeTab: homeTab => dispatch(setHomeTab(homeTab)), openDrawer: () => dispatch(openDrawer()), replaceRoute: route => dispatch(replaceRoute(route)), }; } function mapStateToProps(state) { const globals = state.get('globals'); return { globals }; } export default connect(mapStateToProps, mapDispatchToProps)(About);
docs/app/Examples/addons/Radio/Types/RadioExampleToggle.js
vageeshb/Semantic-UI-React
import React from 'react' import { Radio } from 'semantic-ui-react' const RadioExampleToggle = () => ( <Radio toggle /> ) export default RadioExampleToggle
ajax/libs/intl-tel-input/6.4.0/js/intlTelInput.js
dada0423/cdnjs
/* International Telephone Input v6.4.0 https://github.com/Bluefieldscom/intl-tel-input.git */ // wrap in UMD - see https://github.com/umdjs/umd/blob/master/jqueryPluginCommonjs.js (function(factory) { if (typeof define === "function" && define.amd) { define([ "jquery" ], function($) { factory($, window, document); }); } else if (typeof module === "object" && module.exports) { module.exports = factory(require("jquery"), window, document); } else { factory(jQuery, window, document); } })(function($, window, document, undefined) { "use strict"; // these vars persist through all instances of the plugin var pluginName = "intlTelInput", id = 1, // give each instance it's own id for namespaced event handling defaults = { // typing digits after a valid number will be added to the extension part of the number allowExtensions: false, // automatically format the number according to the selected country autoFormat: true, // if there is just a dial code in the input: remove it on blur, and re-add it on focus autoHideDialCode: true, // add or remove input placeholder with an example number for the selected country autoPlaceholder: true, // default country defaultCountry: "", // append menu to a specific element dropdownContainer: false, // don't display these countries excludeCountries: [], // geoIp lookup function geoIpLookup: null, // don't insert international dial codes nationalMode: true, // number type to use for placeholders numberType: "MOBILE", // display only these countries onlyCountries: [], // the countries at the top of the list. defaults to united states and united kingdom preferredCountries: [ "us", "gb" ], // specify the path to the libphonenumber script to enable validation/formatting utilsScript: "" }, keys = { UP: 38, DOWN: 40, ENTER: 13, ESC: 27, PLUS: 43, A: 65, Z: 90, ZERO: 48, NINE: 57, SPACE: 32, BSPACE: 8, TAB: 9, DEL: 46, CTRL: 17, CMD1: 91, // Chrome CMD2: 224 }, windowLoaded = false; // keep track of if the window.load event has fired as impossible to check after the fact $(window).load(function() { windowLoaded = true; }); function Plugin(element, options) { this.element = element; this.options = $.extend({}, defaults, options); this._defaults = defaults; // event namespace this.ns = "." + pluginName + id++; // Chrome, FF, Safari, IE9+ this.isGoodBrowser = Boolean(element.setSelectionRange); this.hadInitialPlaceholder = Boolean($(element).attr("placeholder")); this._name = pluginName; } Plugin.prototype = { _init: function() { // if in nationalMode, disable options relating to dial codes if (this.options.nationalMode) { this.options.autoHideDialCode = false; } // IE Mobile doesn't support the keypress event (see issue 68) which makes autoFormat impossible if (navigator.userAgent.match(/IEMobile/i)) { this.options.autoFormat = false; } // we cannot just test screen size as some smartphones/website meta tags will report desktop resolutions // Note: for some reason jasmine fucks up if you put this in the main Plugin function with the rest of these declarations // Note: to target Android Mobiles (and not Tablets), we must find "Android" and "Mobile" this.isMobile = /Android.+Mobile|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); // we return these deferred objects from the _init() call so they can be watched, and then we resolve them when each specific request returns // Note: again, jasmine had a spazz when I put these in the Plugin function this.autoCountryDeferred = new $.Deferred(); this.utilsScriptDeferred = new $.Deferred(); // process all the data: onlyCountries, excludeCountries, preferredCountries etc this._processCountryData(); // generate the markup this._generateMarkup(); // set the initial state of the input value and the selected flag this._setInitialState(); // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click this._initListeners(); // utils script, and auto country this._initRequests(); // return the deferreds return [ this.autoCountryDeferred, this.utilsScriptDeferred ]; }, /******************** * PRIVATE METHODS ********************/ // prepare all of the country data, including onlyCountries, excludeCountries and preferredCountries options _processCountryData: function() { // set the instances country data objects this._setInstanceCountryData(); // set the preferredCountries property this._setPreferredCountries(); }, // add a country code to this.countryCodes _addCountryCode: function(iso2, dialCode, priority) { if (!(dialCode in this.countryCodes)) { this.countryCodes[dialCode] = []; } var index = priority || 0; this.countryCodes[dialCode][index] = iso2; }, // process countries processCountries: function(countryArray, processFunc) { var i; // standardise case for (i = 0; i < countryArray.length; i++) { countryArray[i] = countryArray[i].toLowerCase(); } // build instance country array this.countries = []; for (i = 0; i < allCountries.length; i++) { if (processFunc($.inArray(allCountries[i].iso2, countryArray))) { this.countries.push(allCountries[i]); } } }, // process onlyCountries or excludeCountries array if present, and generate the countryCodes map _setInstanceCountryData: function() { // process onlyCountries option if (this.options.onlyCountries.length) { this.processCountries(this.options.onlyCountries, function(inArray) { // if country is in array return inArray != -1; }); } else if (this.options.excludeCountries.length) { this.processCountries(this.options.excludeCountries, function(inArray) { // if country is not in array return inArray == -1; }); } else { this.countries = allCountries; } // generate countryCodes map this.countryCodes = {}; for (var i = 0; i < this.countries.length; i++) { var c = this.countries[i]; this._addCountryCode(c.iso2, c.dialCode, c.priority); // area codes if (c.areaCodes) { for (var j = 0; j < c.areaCodes.length; j++) { // full dial code is country code + dial code this._addCountryCode(c.iso2, c.dialCode + c.areaCodes[j]); } } } }, // process preferred countries - iterate through the preferences, // fetching the country data for each one _setPreferredCountries: function() { this.preferredCountries = []; for (var i = 0; i < this.options.preferredCountries.length; i++) { var countryCode = this.options.preferredCountries[i].toLowerCase(), countryData = this._getCountryData(countryCode, false, true); if (countryData) { this.preferredCountries.push(countryData); } } }, // generate all of the markup for the plugin: the selected flag overlay, and the dropdown _generateMarkup: function() { // telephone input this.telInput = $(this.element); // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can easily put the plugin in an inconsistent state e.g. the wrong flag selected for the autocompleted number, which on submit could mean the wrong number is saved (esp in nationalMode) this.telInput.attr("autocomplete", "off"); // containers (mostly for positioning) this.telInput.wrap($("<div>", { "class": "intl-tel-input" })); this.flagsContainer = $("<div>", { "class": "flag-container" }).insertBefore(this.telInput); // currently selected flag (displayed to left of input) var selectedFlag = $("<div>", { // make element focusable and tab naviagable tabindex: "0", "class": "selected-flag" }).appendTo(this.flagsContainer); this.selectedFlagInner = $("<div>", { "class": "iti-flag" }).appendTo(selectedFlag); // CSS triangle $("<div>", { "class": "arrow" }).appendTo(selectedFlag); // country list // mobile is just a native select element // desktop is a proper list containing: preferred countries, then divider, then all countries if (this.isMobile) { this.countryList = $("<select>", { "class": "iti-mobile-select" }).appendTo(this.flagsContainer); } else { this.countryList = $("<ul>", { "class": "country-list hide" }); if (this.preferredCountries.length && !this.isMobile) { this._appendListItems(this.preferredCountries, "preferred"); $("<li>", { "class": "divider" }).appendTo(this.countryList); } } this._appendListItems(this.countries, ""); if (!this.isMobile) { // this is useful in lots of places this.countryListItems = this.countryList.children(".country"); // create dropdownContainer markup if (this.options.dropdownContainer) { this.dropdown = $("<div>", { "class": "intl-tel-input iti-container" }).append(this.countryList); } else { this.countryList.appendTo(this.flagsContainer); } } }, // add a country <li> to the countryList <ul> container // UPDATE: if isMobile, add an <option> to the countryList <select> container _appendListItems: function(countries, className) { // we create so many DOM elements, it is faster to build a temp string // and then add everything to the DOM in one go at the end var tmp = ""; // for each country for (var i = 0; i < countries.length; i++) { var c = countries[i]; if (this.isMobile) { tmp += "<option data-dial-code='" + c.dialCode + "' value='" + c.iso2 + "'>"; tmp += c.name + " +" + c.dialCode; tmp += "</option>"; } else { // open the list item tmp += "<li class='country " + className + "' data-dial-code='" + c.dialCode + "' data-country-code='" + c.iso2 + "'>"; // add the flag tmp += "<div class='flag'><div class='iti-flag " + c.iso2 + "'></div></div>"; // and the country name and dial code tmp += "<span class='country-name'>" + c.name + "</span>"; tmp += "<span class='dial-code'>+" + c.dialCode + "</span>"; // close the list item tmp += "</li>"; } } this.countryList.append(tmp); }, // set the initial state of the input value and the selected flag _setInitialState: function() { var val = this.telInput.val(); // if there is a number, and it's valid, we can go ahead and set the flag, else fall back to default if (this._getDialCode(val)) { this._updateFlagFromNumber(val, true); } else if (this.options.defaultCountry != "auto") { // check the defaultCountry option, else fall back to the first in the list if (this.options.defaultCountry) { this.options.defaultCountry = this._getCountryData(this.options.defaultCountry.toLowerCase(), false, false); } else { this.options.defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0]; } this._selectFlag(this.options.defaultCountry.iso2); // if empty, insert the default dial code (this function will check !nationalMode and !autoHideDialCode) if (!val) { this._updateDialCode(this.options.defaultCountry.dialCode, false); } } // format if (val) { // this wont be run after _updateDialCode as that's only called if no val this._updateVal(val); } }, // initialise the main event listeners: input keyup, and click selected flag _initListeners: function() { var that = this; this._initKeyListeners(); // autoFormat prevents the change event from firing, so we need to check for changes between focus and blur in order to manually trigger it if (this.options.autoHideDialCode || this.options.autoFormat) { this._initFocusListeners(); } if (this.isMobile) { this.countryList.on("change" + this.ns, function(e) { that._selectListItem($(this).find("option:selected")); }); } else { // hack for input nested inside label: clicking the selected-flag to open the dropdown would then automatically trigger a 2nd click on the input which would close it again var label = this.telInput.closest("label"); if (label.length) { label.on("click" + this.ns, function(e) { // if the dropdown is closed, then focus the input, else ignore the click if (that.countryList.hasClass("hide")) { that.telInput.focus(); } else { e.preventDefault(); } }); } // toggle country dropdown on click var selectedFlag = this.selectedFlagInner.parent(); selectedFlag.on("click" + this.ns, function(e) { // only intercept this event if we're opening the dropdown // else let it bubble up to the top ("click-off-to-close" listener) // we cannot just stopPropagation as it may be needed to close another instance if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled") && !that.telInput.prop("readonly")) { that._showDropdown(); } }); } // open dropdown list if currently focused this.flagsContainer.on("keydown" + that.ns, function(e) { var isDropdownHidden = that.countryList.hasClass("hide"); if (isDropdownHidden && (e.which == keys.UP || e.which == keys.DOWN || e.which == keys.SPACE || e.which == keys.ENTER)) { // prevent form from being submitted if "ENTER" was pressed e.preventDefault(); // prevent event from being handled again by document e.stopPropagation(); that._showDropdown(); } // allow navigation from dropdown to input on TAB if (e.which == keys.TAB) { that._closeDropdown(); } }); }, _initRequests: function() { var that = this; // if the user has specified the path to the utils script, fetch it on window.load if (this.options.utilsScript) { // if the plugin is being initialised after the window.load event has already been fired if (windowLoaded) { this.loadUtils(); } else { // wait until the load event so we don't block any other requests e.g. the flags image $(window).load(function() { that.loadUtils(); }); } } else { this.utilsScriptDeferred.resolve(); } if (this.options.defaultCountry == "auto") { this._loadAutoCountry(); } else { this.autoCountryDeferred.resolve(); } }, _loadAutoCountry: function() { var that = this; // check for cookie var cookieAutoCountry = $.cookie ? $.cookie("itiAutoCountry") : ""; if (cookieAutoCountry) { $.fn[pluginName].autoCountry = cookieAutoCountry; } // 3 options: // 1) already loaded (we're done) // 2) not already started loading (start) // 3) already started loading (do nothing - just wait for loading callback to fire) if ($.fn[pluginName].autoCountry) { this.autoCountryLoaded(); } else if (!$.fn[pluginName].startedLoadingAutoCountry) { // don't do this twice! $.fn[pluginName].startedLoadingAutoCountry = true; if (typeof this.options.geoIpLookup === "function") { this.options.geoIpLookup(function(countryCode) { $.fn[pluginName].autoCountry = countryCode.toLowerCase(); if ($.cookie) { $.cookie("itiAutoCountry", $.fn[pluginName].autoCountry, { path: "/" }); } // tell all instances the auto country is ready // TODO: this should just be the current instances // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight away (e.g. if they have already done the geo ip lookup somewhere else). Using setTimeout means that the current thread of execution will finish before executing this, which allows the plugin to finish initialising. setTimeout(function() { $(".intl-tel-input input").intlTelInput("autoCountryLoaded"); }); }); } } }, _initKeyListeners: function() { var that = this; if (this.options.autoFormat) { // format number and update flag on keypress // use keypress event as we want to ignore all input except for a select few keys, // but we dont want to ignore the navigation keys like the arrows etc. // NOTE: no point in refactoring this to only bind these listeners on focus/blur because then you would need to have those 2 listeners running the whole time anyway... this.telInput.on("keypress" + this.ns, function(e) { // 32 is space, and after that it's all chars (not meta/nav keys) // this fix is needed for Firefox, which triggers keypress event for some meta/nav keys // Update: also ignore if this is a metaKey e.g. FF and Safari trigger keypress on the v of Ctrl+v // Update: also ignore if ctrlKey (FF on Windows/Ubuntu) // Update: also check that we have utils before we do any autoFormat stuff if (e.which >= keys.SPACE && !e.ctrlKey && !e.metaKey && window.intlTelInputUtils && !that.telInput.prop("readonly")) { e.preventDefault(); // allowed keys are just numeric keys and plus // we must allow plus for the case where the user does select-all and then hits plus to start typing a new number. we could refine this logic to first check that the selection contains a plus, but that wont work in old browsers, and I think it's overkill anyway var isAllowedKey = e.which >= keys.ZERO && e.which <= keys.NINE || e.which == keys.PLUS, input = that.telInput[0], noSelection = that.isGoodBrowser && input.selectionStart == input.selectionEnd, max = that.telInput.attr("maxlength"), val = that.telInput.val(), // assumes that if max exists, it is >0 isBelowMax = max ? val.length < max : true; // first: ensure we dont go over maxlength. we must do this here to prevent adding digits in the middle of the number // still reformat even if not an allowed key as they could by typing a formatting char, but ignore if there's a selection as doesn't make sense to replace selection with illegal char and then immediately remove it if (isBelowMax && (isAllowedKey || noSelection)) { var newChar = isAllowedKey ? String.fromCharCode(e.which) : null; that._handleInputKey(newChar, true, isAllowedKey); // if something has changed, trigger the input event (which was otherwised squashed by the preventDefault) if (val != that.telInput.val()) { that.telInput.trigger("input"); } } if (!isAllowedKey) { that._handleInvalidKey(); } } }); } // handle cut/paste event (now supported in all major browsers) this.telInput.on("cut" + this.ns + " paste" + this.ns, function() { // hack because "paste" event is fired before input is updated setTimeout(function() { if (that.options.autoFormat && window.intlTelInputUtils) { var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length; that._handleInputKey(null, cursorAtEnd); that._ensurePlus(); } else { // if no autoFormat, just update flag that._updateFlagFromNumber(that.telInput.val()); } }); }); // handle keyup event // if autoFormat enabled: we use keyup to catch delete events (after the fact) // if no autoFormat, this is used to update the flag this.telInput.on("keyup" + this.ns, function(e) { // the "enter" key event from selecting a dropdown item is triggered here on the input, because the document.keydown handler that initially handles that event triggers a focus on the input, and so the keyup for that same key event gets triggered here. weird, but just make sure we dont bother doing any re-formatting in this case (we've already done preventDefault in the keydown handler, so it wont actually submit the form or anything). // ALSO: ignore keyup if readonly if (e.which == keys.ENTER || that.telInput.prop("readonly")) {} else if (that.options.autoFormat && window.intlTelInputUtils) { // cursorAtEnd defaults to false for bad browsers else they would never get a reformat on delete var cursorAtEnd = that.isGoodBrowser && that.telInput[0].selectionStart == that.telInput.val().length; if (!that.telInput.val()) { // if they just cleared the input, update the flag to the default that._updateFlagFromNumber(""); } else if (e.which == keys.DEL && !cursorAtEnd || e.which == keys.BSPACE) { // if delete in the middle: reformat with no suffix (no need to reformat if delete at end) // if backspace: reformat with no suffix (need to reformat if at end to remove any lingering suffix - this is a feature) // important to remember never to add suffix on any delete key as can fuck up in ie8 so you can never delete a formatting char at the end that._handleInputKey(); } that._ensurePlus(); } else { // if no autoFormat, just update flag that._updateFlagFromNumber(that.telInput.val()); } }); }, // prevent deleting the plus (if not in nationalMode) _ensurePlus: function() { if (!this.options.nationalMode) { var val = this.telInput.val(), input = this.telInput[0]; if (val.charAt(0) != "+") { // newCursorPos is current pos + 1 to account for the plus we are about to add var newCursorPos = this.isGoodBrowser ? input.selectionStart + 1 : 0; this.telInput.val("+" + val); if (this.isGoodBrowser) { input.setSelectionRange(newCursorPos, newCursorPos); } } } }, // alert the user to an invalid key event _handleInvalidKey: function() { var that = this; this.telInput.trigger("invalidkey").addClass("iti-invalid-key"); setTimeout(function() { that.telInput.removeClass("iti-invalid-key"); }, 100); }, // when autoFormat is enabled: handle various key events on the input: // 1) adding a new number character, which will replace any selection, reformat, and preserve the cursor position // 2) reformatting on backspace/delete // 3) cut/paste event _handleInputKey: function(newNumericChar, addSuffix, isAllowedKey) { var val = this.telInput.val(), cleanBefore = this._getClean(val), originalLeftChars, // raw DOM element input = this.telInput[0], digitsOnRight = 0; if (this.isGoodBrowser) { // cursor strategy: maintain the number of digits on the right. we use the right instead of the left so that A) we dont have to account for the new digit (or multiple digits if paste event), and B) we're always on the right side of formatting suffixes digitsOnRight = this._getDigitsOnRight(val, input.selectionEnd); // if handling a new number character: insert it in the right place if (newNumericChar) { // replace any selection they may have made with the new char val = val.substr(0, input.selectionStart) + newNumericChar + val.substring(input.selectionEnd, val.length); } else { // here we're not handling a new char, we're just doing a re-format (e.g. on delete/backspace/paste, after the fact), but we still need to maintain the cursor position. so make note of the char on the left, and then after the re-format, we'll count in the same number of digits from the right, and then keep going through any formatting chars until we hit the same left char that we had before. // UPDATE: now have to store 2 chars as extensions formatting contains 2 spaces so you need to be able to distinguish originalLeftChars = val.substr(input.selectionStart - 2, 2); } } else if (newNumericChar) { val += newNumericChar; } // update the number and flag this.setNumber(val, null, addSuffix, true, isAllowedKey); // update the cursor position if (this.isGoodBrowser) { var newCursor; val = this.telInput.val(); // if it was at the end, keep it there if (!digitsOnRight) { newCursor = val.length; } else { // else count in the same number of digits from the right newCursor = this._getCursorFromDigitsOnRight(val, digitsOnRight); // but if delete/paste etc, keep going left until hit the same left char as before if (!newNumericChar) { newCursor = this._getCursorFromLeftChar(val, newCursor, originalLeftChars); } } // set the new cursor input.setSelectionRange(newCursor, newCursor); } }, // we start from the position in guessCursor, and work our way left until we hit the originalLeftChars or a number to make sure that after reformatting the cursor has the same char on the left in the case of a delete etc _getCursorFromLeftChar: function(val, guessCursor, originalLeftChars) { for (var i = guessCursor; i > 0; i--) { var leftChar = val.charAt(i - 1); if ($.isNumeric(leftChar) || val.substr(i - 2, 2) == originalLeftChars) { return i; } } return 0; }, // after a reformat we need to make sure there are still the same number of digits to the right of the cursor _getCursorFromDigitsOnRight: function(val, digitsOnRight) { for (var i = val.length - 1; i >= 0; i--) { if ($.isNumeric(val.charAt(i))) { if (--digitsOnRight === 0) { return i; } } } return 0; }, // get the number of numeric digits to the right of the cursor so we can reposition the cursor correctly after the reformat has happened _getDigitsOnRight: function(val, selectionEnd) { var digitsOnRight = 0; for (var i = selectionEnd; i < val.length; i++) { if ($.isNumeric(val.charAt(i))) { digitsOnRight++; } } return digitsOnRight; }, // listen for focus and blur _initFocusListeners: function() { var that = this; if (this.options.autoHideDialCode) { // mousedown decides where the cursor goes, so if we're focusing we must preventDefault as we'll be inserting the dial code, and we want the cursor to be at the end no matter where they click this.telInput.on("mousedown" + this.ns, function(e) { if (!that.telInput.is(":focus") && !that.telInput.val()) { e.preventDefault(); // but this also cancels the focus, so we must trigger that manually that.telInput.focus(); } }); } this.telInput.on("focus" + this.ns, function(e) { var value = that.telInput.val(); // save this to compare on blur that.telInput.data("focusVal", value); // on focus: if empty, insert the dial code for the currently selected flag if (that.options.autoHideDialCode && !value && !that.telInput.prop("readonly") && that.selectedCountryData.dialCode) { that._updateVal("+" + that.selectedCountryData.dialCode, null, true); // after auto-inserting a dial code, if the first key they hit is '+' then assume they are entering a new number, so remove the dial code. use keypress instead of keydown because keydown gets triggered for the shift key (required to hit the + key), and instead of keyup because that shows the new '+' before removing the old one that.telInput.one("keypress.plus" + that.ns, function(e) { if (e.which == keys.PLUS) { // if autoFormat is enabled, this key event will have already have been handled by another keypress listener (hence we need to add the "+"). if disabled, it will be handled after this by a keyup listener (hence no need to add the "+"). var newVal = that.options.autoFormat && window.intlTelInputUtils ? "+" : ""; that.telInput.val(newVal); } }); // after tabbing in, make sure the cursor is at the end we must use setTimeout to get outside of the focus handler as it seems the selection happens after that setTimeout(function() { var input = that.telInput[0]; if (that.isGoodBrowser) { var len = that.telInput.val().length; input.setSelectionRange(len, len); } }); } }); this.telInput.on("blur" + this.ns, function() { if (that.options.autoHideDialCode) { // on blur: if just a dial code then remove it var value = that.telInput.val(), startsPlus = value.charAt(0) == "+"; if (startsPlus) { var numeric = that._getNumeric(value); // if just a plus, or if just a dial code if (!numeric || that.selectedCountryData.dialCode == numeric) { that.telInput.val(""); } } // remove the keypress listener we added on focus that.telInput.off("keypress.plus" + that.ns); } // if autoFormat, we must manually trigger change event if value has changed if (that.options.autoFormat && window.intlTelInputUtils && that.telInput.val() != that.telInput.data("focusVal")) { that.telInput.trigger("change"); } }); }, // extract the numeric digits from the given string _getNumeric: function(s) { return s.replace(/\D/g, ""); }, _getClean: function(s) { var prefix = s.charAt(0) == "+" ? "+" : ""; return prefix + this._getNumeric(s); }, // show the dropdown _showDropdown: function() { this._setDropdownPosition(); // update highlighting and scroll to active list item var activeListItem = this.countryList.children(".active"); if (activeListItem.length) { this._highlightListItem(activeListItem); } if (activeListItem.length) { this._scrollTo(activeListItem); } // bind all the dropdown-related listeners: mouseover, click, click-off, keydown this._bindDropdownListeners(); // update the arrow this.selectedFlagInner.children(".arrow").addClass("up"); }, // decide where to position dropdown (depends on position within viewport, and scroll) _setDropdownPosition: function() { var showDropdownContainer = this.options.dropdownContainer && !this.isMobile; if (showDropdownContainer) this.dropdown.appendTo(this.options.dropdownContainer); // show the menu and grab the dropdown height this.dropdownHeight = this.countryList.removeClass("hide").outerHeight(); var that = this, pos = this.telInput.offset(), inputTop = pos.top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom) dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop; // by default, the dropdown will be below the input. If we want to position it above the input, we add the dropup class. this.countryList.toggleClass("dropup", !dropdownFitsBelow && dropdownFitsAbove); // if dropdownContainer is enabled, calculate postion if (showDropdownContainer) { // by default the dropdown will be directly over the input because it's not in the flow. If we want to position it below, we need to add some extra top value. var extraTop = !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.innerHeight(); // calculate placement this.dropdown.css({ top: inputTop + extraTop, left: pos.left }); // close menu on window scroll $(window).on("scroll" + this.ns, function() { that._closeDropdown(); }); } }, // we only bind dropdown listeners when the dropdown is open _bindDropdownListeners: function() { var that = this; // when mouse over a list item, just highlight that one // we add the class "highlight", so if they hit "enter" we know which one to select this.countryList.on("mouseover" + this.ns, ".country", function(e) { that._highlightListItem($(this)); }); // listen for country selection this.countryList.on("click" + this.ns, ".country", function(e) { that._selectListItem($(this)); }); // click off to close // (except when this initial opening click is bubbling up) // we cannot just stopPropagation as it may be needed to close another instance var isOpening = true; $("html").on("click" + this.ns, function(e) { if (!isOpening) { that._closeDropdown(); } isOpening = false; }); // listen for up/down scrolling, enter to select, or letters to jump to country name. // use keydown as keypress doesn't fire for non-char keys and we want to catch if they // just hit down and hold it to scroll down (no keyup event). // listen on the document because that's where key events are triggered if no input has focus var query = "", queryTimer = null; $(document).on("keydown" + this.ns, function(e) { // prevent down key from scrolling the whole page, // and enter key from submitting a form etc e.preventDefault(); if (e.which == keys.UP || e.which == keys.DOWN) { // up and down to navigate that._handleUpDownKey(e.which); } else if (e.which == keys.ENTER) { // enter to select that._handleEnterKey(); } else if (e.which == keys.ESC) { // esc to close that._closeDropdown(); } else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) { // upper case letters (note: keyup/keydown only return upper case letters) // jump to countries that start with the query string if (queryTimer) { clearTimeout(queryTimer); } query += String.fromCharCode(e.which); that._searchForCountry(query); // if the timer hits 1 second, reset the query queryTimer = setTimeout(function() { query = ""; }, 1e3); } }); }, // highlight the next/prev item in the list (and ensure it is visible) _handleUpDownKey: function(key) { var current = this.countryList.children(".highlight").first(); var next = key == keys.UP ? current.prev() : current.next(); if (next.length) { // skip the divider if (next.hasClass("divider")) { next = key == keys.UP ? next.prev() : next.next(); } this._highlightListItem(next); this._scrollTo(next); } }, // select the currently highlighted item _handleEnterKey: function() { var currentCountry = this.countryList.children(".highlight").first(); if (currentCountry.length) { this._selectListItem(currentCountry); } }, // find the first list item whose name starts with the query string _searchForCountry: function(query) { for (var i = 0; i < this.countries.length; i++) { if (this._startsWith(this.countries[i].name, query)) { var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred"); // update highlighting and scroll this._highlightListItem(listItem); this._scrollTo(listItem, true); break; } } }, // check if (uppercase) string a starts with string b _startsWith: function(a, b) { return a.substr(0, b.length).toUpperCase() == b; }, // update the input's value to the given val // if autoFormat=true, format it first according to the country-specific formatting rules // Note: preventConversion will be false (i.e. we allow conversion) on init and when dev calls public method setNumber _updateVal: function(val, format, addSuffix, preventConversion, isAllowedKey) { var formatted; if (this.options.autoFormat && window.intlTelInputUtils && this.selectedCountryData) { if (typeof format == "number" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) { // if user specified a format, and it's a valid number, then format it accordingly formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, format); } else if (!preventConversion && this.options.nationalMode && val.charAt(0) == "+" && intlTelInputUtils.isValidNumber(val, this.selectedCountryData.iso2)) { // if nationalMode and we have a valid intl number, convert it to ntl formatted = intlTelInputUtils.formatNumberByType(val, this.selectedCountryData.iso2, intlTelInputUtils.numberFormat.NATIONAL); } else { // else do the regular AsYouType formatting formatted = intlTelInputUtils.formatNumber(val, this.selectedCountryData.iso2, addSuffix, this.options.allowExtensions, isAllowedKey); } // ensure we dont go over maxlength. we must do this here to truncate any formatting suffix, and also handle paste events var max = this.telInput.attr("maxlength"); if (max && formatted.length > max) { formatted = formatted.substr(0, max); } } else { // no autoFormat, so just insert the original value formatted = val; } this.telInput.val(formatted); }, // check if need to select a new flag based on the given number _updateFlagFromNumber: function(number, updateDefault) { // if we're in nationalMode and we're on US/Canada, make sure the number starts with a +1 so _getDialCode will be able to extract the area code // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag from the number), that means we're initialising the plugin with a number that already has a dial code, so fine to ignore this bit if (number && this.options.nationalMode && this.selectedCountryData && this.selectedCountryData.dialCode == "1" && number.charAt(0) != "+") { if (number.charAt(0) != "1") { number = "1" + number; } number = "+" + number; } // try and extract valid dial code from input var dialCode = this._getDialCode(number), countryCode = null; if (dialCode) { // check if one of the matching countries is already selected var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = this.selectedCountryData && $.inArray(this.selectedCountryData.iso2, countryCodes) != -1; // if a matching country is not already selected (or this is an unknown NANP area code): choose the first in the list if (!alreadySelected || this._isUnknownNanp(number, dialCode)) { // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index for (var j = 0; j < countryCodes.length; j++) { if (countryCodes[j]) { countryCode = countryCodes[j]; break; } } } } else if (number.charAt(0) == "+" && this._getNumeric(number).length) { // invalid dial code, so empty // Note: use getNumeric here because the number has not been formatted yet, so could contain bad shit countryCode = ""; } else if (!number || number == "+") { // empty, or just a plus, so default countryCode = this.options.defaultCountry.iso2; } if (countryCode !== null) { this._selectFlag(countryCode, updateDefault); } }, // check if the given number contains an unknown area code from the North American Numbering Plan i.e. the only dialCode that could be extracted was +1 but the actual number's length is >=4 _isUnknownNanp: function(number, dialCode) { return dialCode == "+1" && this._getNumeric(number).length >= 4; }, // remove highlighting from other list items and highlight the given item _highlightListItem: function(listItem) { this.countryListItems.removeClass("highlight"); listItem.addClass("highlight"); }, // find the country data for the given country code // the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array _getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) { var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries; for (var i = 0; i < countryList.length; i++) { if (countryList[i].iso2 == countryCode) { return countryList[i]; } } if (allowFail) { return null; } else { throw new Error("No country data for '" + countryCode + "'"); } }, // select the given flag, update the placeholder and the active list item _selectFlag: function(countryCode, updateDefault) { // do this first as it will throw an error and stop if countryCode is invalid this.selectedCountryData = countryCode ? this._getCountryData(countryCode, false, false) : {}; // update the "defaultCountry" - we only need the iso2 from now on, so just store that if (updateDefault && this.selectedCountryData.iso2) { // can't just make this equal to selectedCountryData as would be a ref to that object this.options.defaultCountry = { iso2: this.selectedCountryData.iso2 }; } this.selectedFlagInner.attr("class", "iti-flag " + countryCode); // update the selected country's title attribute var title = countryCode ? this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode : "Unknown"; this.selectedFlagInner.parent().attr("title", title); // and the input's placeholder this._updatePlaceholder(); if (this.isMobile) { this.countryList.val(countryCode); } else { // update the active list item this.countryListItems.removeClass("active"); if (countryCode) { this.countryListItems.find(".iti-flag." + countryCode).first().closest(".country").addClass("active"); } } }, // update the input placeholder to an example number from the currently selected country _updatePlaceholder: function() { if (window.intlTelInputUtils && !this.hadInitialPlaceholder && this.options.autoPlaceholder && this.selectedCountryData) { var iso2 = this.selectedCountryData.iso2, numberType = intlTelInputUtils.numberType[this.options.numberType || "FIXED_LINE"], placeholder = iso2 ? intlTelInputUtils.getExampleNumber(iso2, this.options.nationalMode, numberType) : ""; if (typeof this.options.customPlaceholder === "function") { placeholder = this.options.customPlaceholder(placeholder, this.selectedCountryData); } this.telInput.attr("placeholder", placeholder); } }, // called when the user selects a list item from the dropdown _selectListItem: function(listItem) { var countryCodeAttr = this.isMobile ? "value" : "data-country-code"; // update selected flag and active list item this._selectFlag(listItem.attr(countryCodeAttr), true); if (!this.isMobile) { this._closeDropdown(); } this._updateDialCode(listItem.attr("data-dial-code"), true); // always fire the change event as even if nationalMode=true (and we haven't updated the input val), the system as a whole has still changed - see country-sync example. think of it as making a selection from a select element. this.telInput.trigger("change"); // focus the input this.telInput.focus(); // fix for FF and IE11 (with nationalMode=false i.e. auto inserting dial code), who try to put the cursor at the beginning the first time if (this.isGoodBrowser) { var len = this.telInput.val().length; this.telInput[0].setSelectionRange(len, len); } }, // close the dropdown and unbind any listeners _closeDropdown: function() { this.countryList.addClass("hide"); // update the arrow this.selectedFlagInner.children(".arrow").removeClass("up"); // unbind key events $(document).off(this.ns); // unbind click-off-to-close $("html").off(this.ns); // unbind hover and click listeners this.countryList.off(this.ns); // remove menu from container if (this.options.dropdownContainer && !this.isMobile) { $(window).off("scroll" + this.ns); this.dropdown.detach(); } }, // check if an element is visible within it's container, else scroll until it is _scrollTo: function(element, middle) { var container = this.countryList, containerHeight = container.height(), containerTop = container.offset().top, containerBottom = containerTop + containerHeight, elementHeight = element.outerHeight(), elementTop = element.offset().top, elementBottom = elementTop + elementHeight, newScrollTop = elementTop - containerTop + container.scrollTop(), middleOffset = containerHeight / 2 - elementHeight / 2; if (elementTop < containerTop) { // scroll up if (middle) { newScrollTop -= middleOffset; } container.scrollTop(newScrollTop); } else if (elementBottom > containerBottom) { // scroll down if (middle) { newScrollTop += middleOffset; } var heightDifference = containerHeight - elementHeight; container.scrollTop(newScrollTop - heightDifference); } }, // replace any existing dial code with the new one (if not in nationalMode) // also we need to know if we're focusing for a couple of reasons e.g. if so, we want to add any formatting suffix, also if the input is empty and we're not in nationalMode, then we want to insert the dial code _updateDialCode: function(newDialCode, focusing) { var inputVal = this.telInput.val(), newNumber; // save having to pass this every time newDialCode = "+" + newDialCode; if (this.options.nationalMode && inputVal.charAt(0) != "+") { // if nationalMode, we just want to re-format newNumber = inputVal; } else if (inputVal) { // if the previous number contained a valid dial code, replace it // (if more than just a plus character) var prevDialCode = this._getDialCode(inputVal); if (prevDialCode.length > 1) { newNumber = inputVal.replace(prevDialCode, newDialCode); } else { // if the previous number didn't contain a dial code, we should persist it var existingNumber = inputVal.charAt(0) != "+" ? $.trim(inputVal) : ""; newNumber = newDialCode + existingNumber; } } else { newNumber = !this.options.autoHideDialCode || focusing ? newDialCode : ""; } this._updateVal(newNumber, null, focusing); }, // try and extract a valid international dial code from a full telephone number // Note: returns the raw string inc plus character and any whitespace/dots etc _getDialCode: function(number) { var dialCode = ""; // only interested in international numbers (starting with a plus) if (number.charAt(0) == "+") { var numericChars = ""; // iterate over chars for (var i = 0; i < number.length; i++) { var c = number.charAt(i); // if char is number if ($.isNumeric(c)) { numericChars += c; // if current numericChars make a valid dial code if (this.countryCodes[numericChars]) { // store the actual raw string (useful for matching later) dialCode = number.substr(0, i + 1); } // longest dial code is 4 chars if (numericChars.length == 4) { break; } } } } return dialCode; }, /******************** * PUBLIC METHODS ********************/ // this is called when the geoip call returns autoCountryLoaded: function() { if (this.options.defaultCountry == "auto") { this.options.defaultCountry = $.fn[pluginName].autoCountry; this._setInitialState(); this.autoCountryDeferred.resolve(); } }, // remove plugin destroy: function() { if (!this.isMobile) { // make sure the dropdown is closed (and unbind listeners) this._closeDropdown(); } // key events, and focus/blur events if autoHideDialCode=true this.telInput.off(this.ns); if (this.isMobile) { // change event on select country this.countryList.off(this.ns); } else { // click event to open dropdown this.selectedFlagInner.parent().off(this.ns); // label click hack this.telInput.closest("label").off(this.ns); } // remove markup var container = this.telInput.parent(); container.before(this.telInput).remove(); }, // extract the phone number extension if present getExtension: function() { return this.telInput.val().split(" ext. ")[1] || ""; }, // format the number to the given type getNumber: function(type) { if (window.intlTelInputUtils) { return intlTelInputUtils.formatNumberByType(this.telInput.val(), this.selectedCountryData.iso2, type); } return ""; }, // get the type of the entered number e.g. landline/mobile getNumberType: function() { if (window.intlTelInputUtils) { return intlTelInputUtils.getNumberType(this.telInput.val(), this.selectedCountryData.iso2); } return -99; }, // get the country data for the currently selected flag getSelectedCountryData: function() { // if this is undefined, the plugin will return it's instance instead, so in that case an empty object makes more sense return this.selectedCountryData || {}; }, // get the validation error getValidationError: function() { if (window.intlTelInputUtils) { return intlTelInputUtils.getValidationError(this.telInput.val(), this.selectedCountryData.iso2); } return -99; }, // validate the input val - assumes the global function isValidNumber (from utilsScript) isValidNumber: function() { var val = $.trim(this.telInput.val()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : ""; if (window.intlTelInputUtils) { return intlTelInputUtils.isValidNumber(val, countryCode); } return false; }, // load the utils script loadUtils: function(path) { var that = this; var utilsScript = path || this.options.utilsScript; if (utilsScript) { if (!$.fn[pluginName].loadedUtilsScript) { // don't do this twice! (dont just check if the global intlTelInputUtils exists as if init plugin multiple times in quick succession, it may not have finished loading yet) $.fn[pluginName].loadedUtilsScript = true; // dont use $.getScript as it prevents caching $.ajax({ url: utilsScript, complete: function() { // tell all instances that the utils request is complete $(".intl-tel-input input").intlTelInput("utilsRequestComplete"); }, dataType: "script", cache: true }); } } else { this.utilsScriptDeferred.resolve(); } }, // update the selected flag, and update the input val accordingly selectCountry: function(countryCode) { countryCode = countryCode.toLowerCase(); // check if already selected if (!this.selectedFlagInner.hasClass(countryCode)) { this._selectFlag(countryCode, true); this._updateDialCode(this.selectedCountryData.dialCode, false); } }, // set the input value and update the flag setNumber: function(number, format, addSuffix, preventConversion, isAllowedKey) { // ensure starts with plus if (!this.options.nationalMode && number.charAt(0) != "+") { number = "+" + number; } // we must update the flag first, which updates this.selectedCountryData, which is used later for formatting the number before displaying it this._updateFlagFromNumber(number); this._updateVal(number, format, addSuffix, preventConversion, isAllowedKey); }, // this is called when the utils request completes utilsRequestComplete: function() { // if the request was successful if (window.intlTelInputUtils) { // if autoFormat is enabled and there's an initial value in the input, then format it if (this.options.autoFormat && this.telInput.val()) { this._updateVal(this.telInput.val()); } this._updatePlaceholder(); } this.utilsScriptDeferred.resolve(); } }; // adapted to allow public functions // using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate $.fn[pluginName] = function(options) { var args = arguments; // Is the first parameter an object (options), or was omitted, // instantiate a new instance of the plugin. if (options === undefined || typeof options === "object") { var deferreds = []; this.each(function() { if (!$.data(this, "plugin_" + pluginName)) { var instance = new Plugin(this, options); var instanceDeferreds = instance._init(); // we now have 2 deffereds: 1 for auto country, 1 for utils script deferreds.push(instanceDeferreds[0]); deferreds.push(instanceDeferreds[1]); $.data(this, "plugin_" + pluginName, instance); } }); // return the promise from the "master" deferred object that tracks all the others return $.when.apply(null, deferreds); } else if (typeof options === "string" && options[0] !== "_") { // If the first parameter is a string and it doesn't start // with an underscore or "contains" the `init`-function, // treat this as a call to a public method. // Cache the method call to make it possible to return a value var returns; this.each(function() { var instance = $.data(this, "plugin_" + pluginName); // Tests that there's already a plugin-instance // and checks that the requested public method exists if (instance instanceof Plugin && typeof instance[options] === "function") { // Call the method of our plugin instance, // and pass it the supplied arguments. returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1)); } // Allow instances to be destroyed via the 'destroy' method if (options === "destroy") { $.data(this, "plugin_" + pluginName, null); } }); // If the earlier cached method gives a value back return the value, // otherwise return this to preserve chainability. return returns !== undefined ? returns : this; } }; /******************** * STATIC METHODS ********************/ // get the country data object $.fn[pluginName].getCountryData = function() { return allCountries; }; $.fn[pluginName].version = "6.4.0"; // Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers" // jshint -W100 // Array of country objects for the flag dropdown. // Each contains a name, country code (ISO 3166-1 alpha-2) and dial code. // Originally from https://github.com/mledoze/countries // then with a couple of manual re-arrangements to be alphabetical // then changed Kazakhstan from +76 to +7 // and Vatican City from +379 to +39 (see issue 50) // and Caribean Netherlands from +5997 to +599 // and Curacao from +5999 to +599 // Removed: Kosovo, Pitcairn Islands, South Georgia // UPDATE Sept 12th 2015 // List of regions that have iso2 country codes, which I have chosen to omit: // (based on this information: https://en.wikipedia.org/wiki/List_of_country_calling_codes) // AQ - Antarctica - all different country codes depending on which "base" // BV - Bouvet Island - no calling code // GS - South Georgia and the South Sandwich Islands - "inhospitable collection of islands" - same flag and calling code as Falkland Islands // HM - Heard Island and McDonald Islands - no calling code // PN - Pitcairn - tiny population (56), same calling code as New Zealand // TF - French Southern Territories - no calling code // UM - United States Minor Outlying Islands - no calling code // UPDATE the criteria of supported countries or territories (see issue 297) // Have an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 // Have a country calling code: https://en.wikipedia.org/wiki/List_of_country_calling_codes // Have a flag // Must be supported by libphonenumber: https://github.com/googlei18n/libphonenumber // Update: converted objects to arrays to save bytes! // Update: added "priority" for countries with the same dialCode as others // Update: added array of area codes for countries with the same dialCode as others // So each country array has the following information: // [ // Country name, // iso2 code, // International dial code, // Order (if >1 country with same dial code), // Area codes (if >1 country with same dial code) // ] var allCountries = [ [ "Afghanistan (‫افغانستان‬‎)", "af", "93" ], [ "Albania (Shqipëri)", "al", "355" ], [ "Algeria (‫الجزائر‬‎)", "dz", "213" ], [ "American Samoa", "as", "1684" ], [ "Andorra", "ad", "376" ], [ "Angola", "ao", "244" ], [ "Anguilla", "ai", "1264" ], [ "Antigua and Barbuda", "ag", "1268" ], [ "Argentina", "ar", "54" ], [ "Armenia (Հայաստան)", "am", "374" ], [ "Aruba", "aw", "297" ], [ "Australia", "au", "61", 0 ], [ "Austria (Österreich)", "at", "43" ], [ "Azerbaijan (Azərbaycan)", "az", "994" ], [ "Bahamas", "bs", "1242" ], [ "Bahrain (‫البحرين‬‎)", "bh", "973" ], [ "Bangladesh (বাংলাদেশ)", "bd", "880" ], [ "Barbados", "bb", "1246" ], [ "Belarus (Беларусь)", "by", "375" ], [ "Belgium (België)", "be", "32" ], [ "Belize", "bz", "501" ], [ "Benin (Bénin)", "bj", "229" ], [ "Bermuda", "bm", "1441" ], [ "Bhutan (འབྲུག)", "bt", "975" ], [ "Bolivia", "bo", "591" ], [ "Bosnia and Herzegovina (Босна и Херцеговина)", "ba", "387" ], [ "Botswana", "bw", "267" ], [ "Brazil (Brasil)", "br", "55" ], [ "British Indian Ocean Territory", "io", "246" ], [ "British Virgin Islands", "vg", "1284" ], [ "Brunei", "bn", "673" ], [ "Bulgaria (България)", "bg", "359" ], [ "Burkina Faso", "bf", "226" ], [ "Burundi (Uburundi)", "bi", "257" ], [ "Cambodia (កម្ពុជា)", "kh", "855" ], [ "Cameroon (Cameroun)", "cm", "237" ], [ "Canada", "ca", "1", 1, [ "204", "226", "236", "249", "250", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905" ] ], [ "Cape Verde (Kabu Verdi)", "cv", "238" ], [ "Caribbean Netherlands", "bq", "599", 1 ], [ "Cayman Islands", "ky", "1345" ], [ "Central African Republic (République centrafricaine)", "cf", "236" ], [ "Chad (Tchad)", "td", "235" ], [ "Chile", "cl", "56" ], [ "China (中国)", "cn", "86" ], [ "Christmas Island", "cx", "61", 2 ], [ "Cocos (Keeling) Islands", "cc", "61", 1 ], [ "Colombia", "co", "57" ], [ "Comoros (‫جزر القمر‬‎)", "km", "269" ], [ "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243" ], [ "Congo (Republic) (Congo-Brazzaville)", "cg", "242" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "Côte d’Ivoire", "ci", "225" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "Curaçao", "cw", "599", 0 ], [ "Cyprus (Κύπρος)", "cy", "357" ], [ "Czech Republic (Česká republika)", "cz", "420" ], [ "Denmark (Danmark)", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1767" ], [ "Dominican Republic (República Dominicana)", "do", "1", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt (‫مصر‬‎)", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea (Guinea Ecuatorial)", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia (Eesti)", "ee", "372" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands (Islas Malvinas)", "fk", "500" ], [ "Faroe Islands (Føroyar)", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland (Suomi)", "fi", "358", 0 ], [ "France", "fr", "33" ], [ "French Guiana (Guyane française)", "gf", "594" ], [ "French Polynesia (Polynésie française)", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia (საქართველო)", "ge", "995" ], [ "Germany (Deutschland)", "de", "49" ], [ "Ghana (Gaana)", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece (Ελλάδα)", "gr", "30" ], [ "Greenland (Kalaallit Nunaat)", "gl", "299" ], [ "Grenada", "gd", "1473" ], [ "Guadeloupe", "gp", "590", 0 ], [ "Guam", "gu", "1671" ], [ "Guatemala", "gt", "502" ], [ "Guernsey", "gg", "44", 1 ], [ "Guinea (Guinée)", "gn", "224" ], [ "Guinea-Bissau (Guiné Bissau)", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong (香港)", "hk", "852" ], [ "Hungary (Magyarország)", "hu", "36" ], [ "Iceland (Ísland)", "is", "354" ], [ "India (भारत)", "in", "91" ], [ "Indonesia", "id", "62" ], [ "Iran (‫ایران‬‎)", "ir", "98" ], [ "Iraq (‫العراق‬‎)", "iq", "964" ], [ "Ireland", "ie", "353" ], [ "Isle of Man", "im", "44", 2 ], [ "Israel (‫ישראל‬‎)", "il", "972" ], [ "Italy (Italia)", "it", "39", 0 ], [ "Jamaica", "jm", "1876" ], [ "Japan (日本)", "jp", "81" ], [ "Jersey", "je", "44", 3 ], [ "Jordan (‫الأردن‬‎)", "jo", "962" ], [ "Kazakhstan (Казахстан)", "kz", "7", 1 ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "Kuwait (‫الكويت‬‎)", "kw", "965" ], [ "Kyrgyzstan (Кыргызстан)", "kg", "996" ], [ "Laos (ລາວ)", "la", "856" ], [ "Latvia (Latvija)", "lv", "371" ], [ "Lebanon (‫لبنان‬‎)", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya (‫ليبيا‬‎)", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania (Lietuva)", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau (澳門)", "mo", "853" ], [ "Macedonia (FYROM) (Македонија)", "mk", "389" ], [ "Madagascar (Madagasikara)", "mg", "261" ], [ "Malawi", "mw", "265" ], [ "Malaysia", "my", "60" ], [ "Maldives", "mv", "960" ], [ "Mali", "ml", "223" ], [ "Malta", "mt", "356" ], [ "Marshall Islands", "mh", "692" ], [ "Martinique", "mq", "596" ], [ "Mauritania (‫موريتانيا‬‎)", "mr", "222" ], [ "Mauritius (Moris)", "mu", "230" ], [ "Mayotte", "yt", "262", 1 ], [ "Mexico (México)", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova (Republica Moldova)", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia (Монгол)", "mn", "976" ], [ "Montenegro (Crna Gora)", "me", "382" ], [ "Montserrat", "ms", "1664" ], [ "Morocco (‫المغرب‬‎)", "ma", "212", 0 ], [ "Mozambique (Moçambique)", "mz", "258" ], [ "Myanmar (Burma) (မြန်မာ)", "mm", "95" ], [ "Namibia (Namibië)", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal (नेपाल)", "np", "977" ], [ "Netherlands (Nederland)", "nl", "31" ], [ "New Caledonia (Nouvelle-Calédonie)", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger (Nijar)", "ne", "227" ], [ "Nigeria", "ng", "234" ], [ "Niue", "nu", "683" ], [ "Norfolk Island", "nf", "672" ], [ "North Korea (조선 민주주의 인민 공화국)", "kp", "850" ], [ "Northern Mariana Islands", "mp", "1670" ], [ "Norway (Norge)", "no", "47", 0 ], [ "Oman (‫عُمان‬‎)", "om", "968" ], [ "Pakistan (‫پاکستان‬‎)", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine (‫فلسطين‬‎)", "ps", "970" ], [ "Panama (Panamá)", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru (Perú)", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland (Polska)", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", 3, [ "787", "939" ] ], [ "Qatar (‫قطر‬‎)", "qa", "974" ], [ "Réunion (La Réunion)", "re", "262", 0 ], [ "Romania (România)", "ro", "40" ], [ "Russia (Россия)", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint Barthélemy (Saint-Barthélemy)", "bl", "590", 1 ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1869" ], [ "Saint Lucia", "lc", "1758" ], [ "Saint Martin (Saint-Martin (partie française))", "mf", "590", 2 ], [ "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1784" ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "São Tomé and Príncipe (São Tomé e Príncipe)", "st", "239" ], [ "Saudi Arabia (‫المملكة العربية السعودية‬‎)", "sa", "966" ], [ "Senegal (Sénégal)", "sn", "221" ], [ "Serbia (Србија)", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1721" ], [ "Slovakia (Slovensko)", "sk", "421" ], [ "Slovenia (Slovenija)", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia (Soomaaliya)", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea (대한민국)", "kr", "82" ], [ "South Sudan (‫جنوب السودان‬‎)", "ss", "211" ], [ "Spain (España)", "es", "34" ], [ "Sri Lanka (ශ්‍රී ලංකාව)", "lk", "94" ], [ "Sudan (‫السودان‬‎)", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Svalbard and Jan Mayen", "sj", "47", 1 ], [ "Swaziland", "sz", "268" ], [ "Sweden (Sverige)", "se", "46" ], [ "Switzerland (Schweiz)", "ch", "41" ], [ "Syria (‫سوريا‬‎)", "sy", "963" ], [ "Taiwan (台灣)", "tw", "886" ], [ "Tajikistan", "tj", "992" ], [ "Tanzania", "tz", "255" ], [ "Thailand (ไทย)", "th", "66" ], [ "Timor-Leste", "tl", "670" ], [ "Togo", "tg", "228" ], [ "Tokelau", "tk", "690" ], [ "Tonga", "to", "676" ], [ "Trinidad and Tobago", "tt", "1868" ], [ "Tunisia (‫تونس‬‎)", "tn", "216" ], [ "Turkey (Türkiye)", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks and Caicos Islands", "tc", "1649" ], [ "Tuvalu", "tv", "688" ], [ "U.S. Virgin Islands", "vi", "1340" ], [ "Uganda", "ug", "256" ], [ "Ukraine (Україна)", "ua", "380" ], [ "United Arab Emirates (‫الإمارات العربية المتحدة‬‎)", "ae", "971" ], [ "United Kingdom", "gb", "44", 0 ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "Uzbekistan (Oʻzbekiston)", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City (Città del Vaticano)", "va", "39", 1 ], [ "Venezuela", "ve", "58" ], [ "Vietnam (Việt Nam)", "vn", "84" ], [ "Wallis and Futuna", "wf", "681" ], [ "Western Sahara (‫الصحراء الغربية‬‎)", "eh", "212", 1 ], [ "Yemen (‫اليمن‬‎)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ], [ "Åland Islands", "ax", "358", 1 ] ]; // loop over all of the countries above for (var i = 0; i < allCountries.length; i++) { var c = allCountries[i]; allCountries[i] = { name: c[0], iso2: c[1], dialCode: c[2], priority: c[3] || 0, areaCodes: c[4] || null }; } });
src/index.js
thinq4yourself/simply-social-in
import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import React from 'react'; import { store, history} from './store'; import { Route, Switch } from 'react-router-dom'; import { ConnectedRouter } from 'react-router-redux'; import App from './components/App'; ReactDOM.render(( <Provider store={store}> <ConnectedRouter history={history}> <Switch> <Route path="/" component={App} /> </Switch> </ConnectedRouter> </Provider> ), document.getElementById('root'));
app/javascript/mastodon/features/compose/components/emoji_picker_dropdown.js
honpya/taketodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import { EmojiPicker as EmojiPickerAsync } from '../../ui/util/async-components'; import Overlay from 'react-overlays/lib/Overlay'; import classNames from 'classnames'; import ImmutablePropTypes from 'react-immutable-proptypes'; import detectPassiveEvents from 'detect-passive-events'; import { buildCustomEmojis } from '../../emoji/emoji'; const messages = defineMessages({ emoji: { id: 'emoji_button.label', defaultMessage: 'Insert emoji' }, emoji_search: { id: 'emoji_button.search', defaultMessage: 'Search...' }, emoji_not_found: { id: 'emoji_button.not_found', defaultMessage: 'No emojos!! (╯°□°)╯︵ ┻━┻' }, custom: { id: 'emoji_button.custom', defaultMessage: 'Custom' }, recent: { id: 'emoji_button.recent', defaultMessage: 'Frequently used' }, search_results: { id: 'emoji_button.search_results', defaultMessage: 'Search results' }, people: { id: 'emoji_button.people', defaultMessage: 'People' }, nature: { id: 'emoji_button.nature', defaultMessage: 'Nature' }, food: { id: 'emoji_button.food', defaultMessage: 'Food & Drink' }, activity: { id: 'emoji_button.activity', defaultMessage: 'Activity' }, travel: { id: 'emoji_button.travel', defaultMessage: 'Travel & Places' }, objects: { id: 'emoji_button.objects', defaultMessage: 'Objects' }, symbols: { id: 'emoji_button.symbols', defaultMessage: 'Symbols' }, flags: { id: 'emoji_button.flags', defaultMessage: 'Flags' }, }); const assetHost = process.env.CDN_HOST || ''; let EmojiPicker, Emoji; // load asynchronously const backgroundImageFn = () => `${assetHost}/emoji/sheet.png`; const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false; const categoriesSort = [ 'recent', 'custom', 'people', 'nature', 'foods', 'activity', 'places', 'objects', 'symbols', 'flags', ]; class ModifierPickerMenu extends React.PureComponent { static propTypes = { active: PropTypes.bool, onSelect: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, }; handleClick = e => { this.props.onSelect(e.currentTarget.getAttribute('data-index') * 1); } componentWillReceiveProps (nextProps) { if (nextProps.active) { this.attachListeners(); } else { this.removeListeners(); } } componentWillUnmount () { this.removeListeners(); } handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } attachListeners () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); } removeListeners () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } render () { const { active } = this.props; return ( <div className='emoji-picker-dropdown__modifiers__menu' style={{ display: active ? 'block' : 'none' }} ref={this.setRef}> <button onClick={this.handleClick} data-index={1}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={1} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={2}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={2} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={3}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={3} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={4}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={4} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={5}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={5} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={6}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={6} backgroundImageFn={backgroundImageFn} /></button> </div> ); } } class ModifierPicker extends React.PureComponent { static propTypes = { active: PropTypes.bool, modifier: PropTypes.number, onChange: PropTypes.func, onClose: PropTypes.func, onOpen: PropTypes.func, }; handleClick = () => { if (this.props.active) { this.props.onClose(); } else { this.props.onOpen(); } } handleSelect = modifier => { this.props.onChange(modifier); this.props.onClose(); } render () { const { active, modifier } = this.props; return ( <div className='emoji-picker-dropdown__modifiers'> <Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={modifier} onClick={this.handleClick} backgroundImageFn={backgroundImageFn} /> <ModifierPickerMenu active={active} onSelect={this.handleSelect} onClose={this.props.onClose} /> </div> ); } } @injectIntl class EmojiPickerMenu extends React.PureComponent { static propTypes = { custom_emojis: ImmutablePropTypes.list, frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string), loading: PropTypes.bool, onClose: PropTypes.func.isRequired, onPick: PropTypes.func.isRequired, style: PropTypes.object, placement: PropTypes.string, arrowOffsetLeft: PropTypes.string, arrowOffsetTop: PropTypes.string, intl: PropTypes.object.isRequired, skinTone: PropTypes.number.isRequired, onSkinTone: PropTypes.func.isRequired, }; static defaultProps = { style: {}, loading: true, placement: 'bottom', frequentlyUsedEmojis: [], }; state = { modifierOpen: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } getI18n = () => { const { intl } = this.props; return { search: intl.formatMessage(messages.emoji_search), notfound: intl.formatMessage(messages.emoji_not_found), categories: { search: intl.formatMessage(messages.search_results), recent: intl.formatMessage(messages.recent), people: intl.formatMessage(messages.people), nature: intl.formatMessage(messages.nature), foods: intl.formatMessage(messages.food), activity: intl.formatMessage(messages.activity), places: intl.formatMessage(messages.travel), objects: intl.formatMessage(messages.objects), symbols: intl.formatMessage(messages.symbols), flags: intl.formatMessage(messages.flags), custom: intl.formatMessage(messages.custom), }, }; } handleClick = emoji => { if (!emoji.native) { emoji.native = emoji.colons; } this.props.onClose(); this.props.onPick(emoji); } handleModifierOpen = () => { this.setState({ modifierOpen: true }); } handleModifierClose = () => { this.setState({ modifierOpen: false }); } handleModifierChange = modifier => { this.props.onSkinTone(modifier); } render () { const { loading, style, intl, custom_emojis, skinTone, frequentlyUsedEmojis } = this.props; if (loading) { return <div style={{ width: 299 }} />; } const title = intl.formatMessage(messages.emoji); const { modifierOpen } = this.state; return ( <div className={classNames('emoji-picker-dropdown__menu', { selecting: modifierOpen })} style={style} ref={this.setRef}> <EmojiPicker perLine={8} emojiSize={22} sheetSize={32} custom={buildCustomEmojis(custom_emojis)} color='' emoji='' set='twitter' title={title} i18n={this.getI18n()} onClick={this.handleClick} include={categoriesSort} recent={frequentlyUsedEmojis} skin={skinTone} showPreview={false} backgroundImageFn={backgroundImageFn} emojiTooltip /> <ModifierPicker active={modifierOpen} modifier={skinTone} onOpen={this.handleModifierOpen} onClose={this.handleModifierClose} onChange={this.handleModifierChange} /> </div> ); } } @injectIntl export default class EmojiPickerDropdown extends React.PureComponent { static propTypes = { custom_emojis: ImmutablePropTypes.list, frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string), intl: PropTypes.object.isRequired, onPickEmoji: PropTypes.func.isRequired, onSkinTone: PropTypes.func.isRequired, skinTone: PropTypes.number.isRequired, }; state = { active: false, loading: false, }; setRef = (c) => { this.dropdown = c; } onShowDropdown = () => { this.setState({ active: true }); if (!EmojiPicker) { this.setState({ loading: true }); EmojiPickerAsync().then(EmojiMart => { EmojiPicker = EmojiMart.Picker; Emoji = EmojiMart.Emoji; this.setState({ loading: false }); }).catch(() => { this.setState({ loading: false }); }); } } onHideDropdown = () => { this.setState({ active: false }); } onToggle = (e) => { if (!this.state.loading && (!e.key || e.key === 'Enter')) { if (this.state.active) { this.onHideDropdown(); } else { this.onShowDropdown(); } } } handleKeyDown = e => { if (e.key === 'Escape') { this.onHideDropdown(); } } setTargetRef = c => { this.target = c; } findTarget = () => { return this.target; } render () { const { intl, onPickEmoji, onSkinTone, skinTone, frequentlyUsedEmojis } = this.props; const title = intl.formatMessage(messages.emoji); const { active, loading } = this.state; return ( <div className='emoji-picker-dropdown' onKeyDown={this.handleKeyDown}> <div ref={this.setTargetRef} className='emoji-button' title={title} aria-label={title} aria-expanded={active} role='button' onClick={this.onToggle} onKeyDown={this.onToggle} tabIndex={0}> <img className={classNames('emojione', { 'pulse-loading': active && loading })} alt='🙂' src={`${assetHost}/emoji/1f602.svg`} /> </div> <Overlay show={active} placement='bottom' target={this.findTarget}> <EmojiPickerMenu custom_emojis={this.props.custom_emojis} loading={loading} onClose={this.onHideDropdown} onPick={onPickEmoji} onSkinTone={onSkinTone} skinTone={skinTone} frequentlyUsedEmojis={frequentlyUsedEmojis} /> </Overlay> </div> ); } }
node_modules/react-icons/md/flash-auto.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const MdFlashAuto = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m28 12.7h4l-2-6.1z m3.6-9.3l5.4 15h-3.2l-1.1-3.4h-5.4l-1.1 3.4h-3.2l5.4-15h3.2z m-26.6 0h16.6l-6.6 15h6.6l-11.6 20v-15h-5v-20z"/></g> </Icon> ) export default MdFlashAuto
fields/types/color/ColorField.js
wmertens/keystone
import ColorPicker from 'react-color'; import Field from '../Field'; import React from 'react'; import { FormInput, InputGroup } from 'elemental'; const PICKER_TYPES = ['chrome', 'compact', 'material', 'photoshop', 'sketch', 'slider', 'swatches']; const TRANSPARENT_BG = `<svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g fill="#CCCCCC"> <path d="M0,0 L8,0 L8,8 L0,8 L0,0 Z M8,8 L16,8 L16,16 L8,16 L8,8 Z M0,16 L8,16 L8,24 L0,24 L0,16 Z M16,0 L24,0 L24,8 L16,8 L16,0 Z M16,16 L24,16 L24,24 L16,24 L16,16 Z" /> </g> </svg>`; module.exports = Field.create({ displayName: 'ColorField', propTypes: { onChange: React.PropTypes.func, path: React.PropTypes.string, pickerType: React.PropTypes.oneOf(PICKER_TYPES), value: React.PropTypes.string, }, getInitialState () { return { displayColorPicker: false, }; }, getDefaultProps () { return { pickerType: 'sketch', }; }, updateValue (value) { this.props.onChange({ path: this.props.path, value: value, }); }, handleInputChange (event) { var newValue = event.target.value; if (/^([0-9A-F]{3}){1,2}$/.test(newValue)) { newValue = '#' + newValue; } if (newValue === this.props.value) return; this.updateValue(newValue); }, handleClick () { this.setState({ displayColorPicker: !this.state.displayColorPicker }); }, handleClose () { this.setState({ displayColorPicker: false }); }, handlePickerChange (color) { var newValue = '#' + color.hex; if (newValue === this.props.value) return; this.updateValue(newValue); }, renderSwatch () { return (this.props.value) ? ( <span className="field-type-color__swatch" style={{ backgroundColor: this.props.value }} /> ) : ( <span className="field-type-color__swatch" dangerouslySetInnerHTML={{ __html: TRANSPARENT_BG }} /> ); }, renderField () { return ( <div className="field-type-color__wrapper"> <InputGroup> <InputGroup.Section grow> <FormInput ref="field" onChange={this.valueChanged} name={this.props.path} value={this.props.value} autoComplete="off" /> </InputGroup.Section> <InputGroup.Section> <button type="button" onClick={this.handleClick} className="FormInput FormSelect field-type-color__button"> {this.renderSwatch()} </button> </InputGroup.Section> </InputGroup> <div className="field-type-color__picker"> <ColorPicker color={this.props.value} display={this.state.displayColorPicker} onChangeComplete={this.handlePickerChange} onClose={this.handleClose} position={window.innerWidth > 480 ? 'right' : 'below'} type={this.props.pickerType} /> </div> </div> ); }, });
examples/app.js
Corilla/corilla-components
import React from 'react'; import { render } from 'react-dom'; import { MarkdownPreview } from '../lib/MarkdownPreview'; import './style.scss'; const ExampleApp = () => ( <div> <h1>Corilla React UI Components</h1> <section> <h2>MarkdownPreview</h2> <article> <h3>Example</h3> <MarkdownPreview text={'# H1'} /> <MarkdownPreview text={'## H2'} /> <MarkdownPreview text={'*Italic text*'} /> <MarkdownPreview text={'**Bold list title**'} /> <MarkdownPreview text={'1. item 1\n 1. item 2\n 1. item 3'} /> </article> </section> </div> ); render( <ExampleApp />, document.getElementById('example-app') );
src/containers/LanguageSwitcher/withModal.js
EncontrAR/backoffice
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Modal from '../../components/feedback/modal'; import Button from '../../components/uielements/button'; import actions from '../../redux/languageSwitcher/actions'; import config from './config'; const { switchActivation, changeLanguage } = actions; class LanguageSwitcher extends Component { render() { const { isActivated, language, switchActivation, changeLanguage } = this.props; return ( <div className="isoButtonWrapper"> <Button type="primary" className="" onClick={switchActivation}> Switch Language </Button> <Modal title={'Select Language'} visible={isActivated} onCancel={switchActivation} cancelText="Cancel" footer={[]} > <div> {config.options.map(option => { const { languageId, text } = option; const type = languageId === language.languageId ? 'primary' : 'success'; return ( <Button type={type} key={languageId} onClick={() => { changeLanguage(languageId); }} > {text} </Button> ); })} </div> </Modal> </div> ); } } export default connect( state => ({ ...state.LanguageSwitcher.toJS() }), { switchActivation, changeLanguage } )(LanguageSwitcher);
ajax/libs/react-bootstrap/0.30.0-rc.1/react-bootstrap.js
cdnjs/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactBootstrap"] = factory(require("react"), require("react-dom")); else root["ReactBootstrap"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_30__, __WEBPACK_EXTERNAL_MODULE_61__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; var _interopRequireWildcard = __webpack_require__(2)['default']; exports.__esModule = true; var _Accordion2 = __webpack_require__(3); var _Accordion3 = _interopRequireDefault(_Accordion2); exports.Accordion = _Accordion3['default']; var _Alert2 = __webpack_require__(44); var _Alert3 = _interopRequireDefault(_Alert2); exports.Alert = _Alert3['default']; var _Badge2 = __webpack_require__(48); var _Badge3 = _interopRequireDefault(_Badge2); exports.Badge = _Badge3['default']; var _Breadcrumb2 = __webpack_require__(49); var _Breadcrumb3 = _interopRequireDefault(_Breadcrumb2); exports.Breadcrumb = _Breadcrumb3['default']; var _BreadcrumbItem2 = __webpack_require__(50); var _BreadcrumbItem3 = _interopRequireDefault(_BreadcrumbItem2); exports.BreadcrumbItem = _BreadcrumbItem3['default']; var _Button2 = __webpack_require__(54); var _Button3 = _interopRequireDefault(_Button2); exports.Button = _Button3['default']; var _ButtonGroup2 = __webpack_require__(55); var _ButtonGroup3 = _interopRequireDefault(_ButtonGroup2); exports.ButtonGroup = _ButtonGroup3['default']; var _ButtonToolbar2 = __webpack_require__(57); var _ButtonToolbar3 = _interopRequireDefault(_ButtonToolbar2); exports.ButtonToolbar = _ButtonToolbar3['default']; var _Carousel2 = __webpack_require__(58); var _Carousel3 = _interopRequireDefault(_Carousel2); exports.Carousel = _Carousel3['default']; var _CarouselItem2 = __webpack_require__(60); var _CarouselItem3 = _interopRequireDefault(_CarouselItem2); exports.CarouselItem = _CarouselItem3['default']; var _Checkbox2 = __webpack_require__(64); var _Checkbox3 = _interopRequireDefault(_Checkbox2); exports.Checkbox = _Checkbox3['default']; var _Clearfix2 = __webpack_require__(66); var _Clearfix3 = _interopRequireDefault(_Clearfix2); exports.Clearfix = _Clearfix3['default']; var _ControlLabel2 = __webpack_require__(68); var _ControlLabel3 = _interopRequireDefault(_ControlLabel2); exports.ControlLabel = _ControlLabel3['default']; var _Col2 = __webpack_require__(69); var _Col3 = _interopRequireDefault(_Col2); exports.Col = _Col3['default']; var _Collapse2 = __webpack_require__(70); var _Collapse3 = _interopRequireDefault(_Collapse2); exports.Collapse = _Collapse3['default']; var _Dropdown2 = __webpack_require__(83); var _Dropdown3 = _interopRequireDefault(_Dropdown2); exports.Dropdown = _Dropdown3['default']; var _DropdownButton2 = __webpack_require__(125); var _DropdownButton3 = _interopRequireDefault(_DropdownButton2); exports.DropdownButton = _DropdownButton3['default']; var _Fade2 = __webpack_require__(127); var _Fade3 = _interopRequireDefault(_Fade2); exports.Fade = _Fade3['default']; var _Form2 = __webpack_require__(128); var _Form3 = _interopRequireDefault(_Form2); exports.Form = _Form3['default']; var _FormControl2 = __webpack_require__(129); var _FormControl3 = _interopRequireDefault(_FormControl2); exports.FormControl = _FormControl3['default']; var _FormGroup2 = __webpack_require__(132); var _FormGroup3 = _interopRequireDefault(_FormGroup2); exports.FormGroup = _FormGroup3['default']; var _Glyphicon2 = __webpack_require__(63); var _Glyphicon3 = _interopRequireDefault(_Glyphicon2); exports.Glyphicon = _Glyphicon3['default']; var _Grid2 = __webpack_require__(133); var _Grid3 = _interopRequireDefault(_Grid2); exports.Grid = _Grid3['default']; var _HelpBlock2 = __webpack_require__(134); var _HelpBlock3 = _interopRequireDefault(_HelpBlock2); exports.HelpBlock = _HelpBlock3['default']; var _Image2 = __webpack_require__(135); var _Image3 = _interopRequireDefault(_Image2); exports.Image = _Image3['default']; var _InputGroup2 = __webpack_require__(136); var _InputGroup3 = _interopRequireDefault(_InputGroup2); exports.InputGroup = _InputGroup3['default']; var _Jumbotron2 = __webpack_require__(139); var _Jumbotron3 = _interopRequireDefault(_Jumbotron2); exports.Jumbotron = _Jumbotron3['default']; var _Label2 = __webpack_require__(140); var _Label3 = _interopRequireDefault(_Label2); exports.Label = _Label3['default']; var _ListGroup2 = __webpack_require__(141); var _ListGroup3 = _interopRequireDefault(_ListGroup2); exports.ListGroup = _ListGroup3['default']; var _ListGroupItem2 = __webpack_require__(142); var _ListGroupItem3 = _interopRequireDefault(_ListGroupItem2); exports.ListGroupItem = _ListGroupItem3['default']; var _Media2 = __webpack_require__(143); var _Media3 = _interopRequireDefault(_Media2); exports.Media = _Media3['default']; var _MenuItem2 = __webpack_require__(150); var _MenuItem3 = _interopRequireDefault(_MenuItem2); exports.MenuItem = _MenuItem3['default']; var _Modal2 = __webpack_require__(151); var _Modal3 = _interopRequireDefault(_Modal2); exports.Modal = _Modal3['default']; var _ModalBody2 = __webpack_require__(169); var _ModalBody3 = _interopRequireDefault(_ModalBody2); exports.ModalBody = _ModalBody3['default']; var _ModalFooter2 = __webpack_require__(171); var _ModalFooter3 = _interopRequireDefault(_ModalFooter2); exports.ModalFooter = _ModalFooter3['default']; var _ModalHeader2 = __webpack_require__(172); var _ModalHeader3 = _interopRequireDefault(_ModalHeader2); exports.ModalHeader = _ModalHeader3['default']; var _ModalTitle2 = __webpack_require__(173); var _ModalTitle3 = _interopRequireDefault(_ModalTitle2); exports.ModalTitle = _ModalTitle3['default']; var _Nav2 = __webpack_require__(174); var _Nav3 = _interopRequireDefault(_Nav2); exports.Nav = _Nav3['default']; var _Navbar2 = __webpack_require__(175); var _Navbar3 = _interopRequireDefault(_Navbar2); exports.Navbar = _Navbar3['default']; var _NavbarBrand2 = __webpack_require__(176); var _NavbarBrand3 = _interopRequireDefault(_NavbarBrand2); exports.NavbarBrand = _NavbarBrand3['default']; var _NavDropdown2 = __webpack_require__(180); var _NavDropdown3 = _interopRequireDefault(_NavDropdown2); exports.NavDropdown = _NavDropdown3['default']; var _NavItem2 = __webpack_require__(181); var _NavItem3 = _interopRequireDefault(_NavItem2); exports.NavItem = _NavItem3['default']; var _Overlay2 = __webpack_require__(182); var _Overlay3 = _interopRequireDefault(_Overlay2); exports.Overlay = _Overlay3['default']; var _OverlayTrigger2 = __webpack_require__(191); var _OverlayTrigger3 = _interopRequireDefault(_OverlayTrigger2); exports.OverlayTrigger = _OverlayTrigger3['default']; var _PageHeader2 = __webpack_require__(192); var _PageHeader3 = _interopRequireDefault(_PageHeader2); exports.PageHeader = _PageHeader3['default']; var _PageItem2 = __webpack_require__(193); var _PageItem3 = _interopRequireDefault(_PageItem2); exports.PageItem = _PageItem3['default']; var _Pager2 = __webpack_require__(196); var _Pager3 = _interopRequireDefault(_Pager2); exports.Pager = _Pager3['default']; var _Pagination2 = __webpack_require__(197); var _Pagination3 = _interopRequireDefault(_Pagination2); exports.Pagination = _Pagination3['default']; var _Panel2 = __webpack_require__(199); var _Panel3 = _interopRequireDefault(_Panel2); exports.Panel = _Panel3['default']; var _PanelGroup2 = __webpack_require__(31); var _PanelGroup3 = _interopRequireDefault(_PanelGroup2); exports.PanelGroup = _PanelGroup3['default']; var _Popover2 = __webpack_require__(200); var _Popover3 = _interopRequireDefault(_Popover2); exports.Popover = _Popover3['default']; var _ProgressBar2 = __webpack_require__(201); var _ProgressBar3 = _interopRequireDefault(_ProgressBar2); exports.ProgressBar = _ProgressBar3['default']; var _Radio2 = __webpack_require__(202); var _Radio3 = _interopRequireDefault(_Radio2); exports.Radio = _Radio3['default']; var _ResponsiveEmbed2 = __webpack_require__(203); var _ResponsiveEmbed3 = _interopRequireDefault(_ResponsiveEmbed2); exports.ResponsiveEmbed = _ResponsiveEmbed3['default']; var _Row2 = __webpack_require__(204); var _Row3 = _interopRequireDefault(_Row2); exports.Row = _Row3['default']; var _SafeAnchor2 = __webpack_require__(51); var _SafeAnchor3 = _interopRequireDefault(_SafeAnchor2); exports.SafeAnchor = _SafeAnchor3['default']; var _SplitButton2 = __webpack_require__(205); var _SplitButton3 = _interopRequireDefault(_SplitButton2); exports.SplitButton = _SplitButton3['default']; var _Tab2 = __webpack_require__(207); var _Tab3 = _interopRequireDefault(_Tab2); exports.Tab = _Tab3['default']; var _TabContainer2 = __webpack_require__(208); var _TabContainer3 = _interopRequireDefault(_TabContainer2); exports.TabContainer = _TabContainer3['default']; var _TabContent2 = __webpack_require__(209); var _TabContent3 = _interopRequireDefault(_TabContent2); exports.TabContent = _TabContent3['default']; var _Table2 = __webpack_require__(211); var _Table3 = _interopRequireDefault(_Table2); exports.Table = _Table3['default']; var _TabPane2 = __webpack_require__(210); var _TabPane3 = _interopRequireDefault(_TabPane2); exports.TabPane = _TabPane3['default']; var _Tabs2 = __webpack_require__(212); var _Tabs3 = _interopRequireDefault(_Tabs2); exports.Tabs = _Tabs3['default']; var _Thumbnail2 = __webpack_require__(213); var _Thumbnail3 = _interopRequireDefault(_Thumbnail2); exports.Thumbnail = _Thumbnail3['default']; var _Tooltip2 = __webpack_require__(214); var _Tooltip3 = _interopRequireDefault(_Tooltip2); exports.Tooltip = _Tooltip3['default']; var _Well2 = __webpack_require__(215); var _Well3 = _interopRequireDefault(_Well2); exports.Well = _Well3['default']; var _utils2 = __webpack_require__(216); var _utils = _interopRequireWildcard(_utils2); exports.utils = _utils; /***/ }, /* 1 */ /***/ function(module, exports) { "use strict"; exports["default"] = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; exports.__esModule = true; /***/ }, /* 2 */ /***/ function(module, exports) { "use strict"; exports["default"] = function (obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }; exports.__esModule = true; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _PanelGroup = __webpack_require__(31); var _PanelGroup2 = _interopRequireDefault(_PanelGroup); var Accordion = (function (_React$Component) { _inherits(Accordion, _React$Component); function Accordion() { _classCallCheck(this, Accordion); _React$Component.apply(this, arguments); } Accordion.prototype.render = function render() { return _react2['default'].createElement( _PanelGroup2['default'], _extends({}, this.props, { accordion: true }), this.props.children ); }; return Accordion; })(_react2['default'].Component); exports['default'] = Accordion; module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$create = __webpack_require__(5)["default"]; var _Object$setPrototypeOf = __webpack_require__(8)["default"]; exports["default"] = 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; }; exports.__esModule = true; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(6), __esModule: true }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(7); module.exports = function create(P, D){ return $.create(P, D); }; /***/ }, /* 7 */ /***/ function(module, exports) { var $Object = Object; module.exports = { create: $Object.create, getProto: $Object.getPrototypeOf, isEnum: {}.propertyIsEnumerable, getDesc: $Object.getOwnPropertyDescriptor, setDesc: $Object.defineProperty, setDescs: $Object.defineProperties, getKeys: $Object.keys, getNames: $Object.getOwnPropertyNames, getSymbols: $Object.getOwnPropertySymbols, each: [].forEach }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(9), __esModule: true }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(10); module.exports = __webpack_require__(13).Object.setPrototypeOf; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(11); $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(16).set}); /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(12) , core = __webpack_require__(13) , ctx = __webpack_require__(14) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && key in target; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(param){ return this instanceof C ? new C(param) : C(param); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out; } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap module.exports = $export; /***/ }, /* 12 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 13 */ /***/ function(module, exports) { var core = module.exports = {version: '1.2.6'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(15); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }, /* 15 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var getDesc = __webpack_require__(7).getDesc , isObject = __webpack_require__(17) , anObject = __webpack_require__(18); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = __webpack_require__(14)(Function.call, getDesc(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }, /* 17 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(17); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 19 */ /***/ function(module, exports) { "use strict"; exports["default"] = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; exports.__esModule = true; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$assign = __webpack_require__(21)["default"]; exports["default"] = _Object$assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.__esModule = true; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(22), __esModule: true }; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(23); module.exports = __webpack_require__(13).Object.assign; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(11); $export($export.S + $export.F, 'Object', {assign: __webpack_require__(24)}); /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.1 Object.assign(target, source, ...) var $ = __webpack_require__(7) , toObject = __webpack_require__(25) , IObject = __webpack_require__(27); // should work with symbols and should have deterministic property order (V8 bug) module.exports = __webpack_require__(29)(function(){ var a = Object.assign , A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , $$ = arguments , $$len = $$.length , index = 1 , getKeys = $.getKeys , getSymbols = $.getSymbols , isEnum = $.isEnum; while($$len > index){ var S = IObject($$[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : Object.assign; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(26); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 26 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(28); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 28 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 29 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 30 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_30__; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _Object$assign = __webpack_require__(21)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var propTypes = { accordion: _react2['default'].PropTypes.bool, activeKey: _react2['default'].PropTypes.any, defaultActiveKey: _react2['default'].PropTypes.any, onSelect: _react2['default'].PropTypes.func, role: _react2['default'].PropTypes.string }; var defaultProps = { accordion: false }; // TODO: Use uncontrollable. var PanelGroup = (function (_React$Component) { _inherits(PanelGroup, _React$Component); function PanelGroup(props, context) { _classCallCheck(this, PanelGroup); _React$Component.call(this, props, context); this.handleSelect = this.handleSelect.bind(this); this.state = { activeKey: props.defaultActiveKey }; } PanelGroup.prototype.handleSelect = function handleSelect(key, e) { e.preventDefault(); if (this.props.onSelect) { this.props.onSelect(key, e); } if (this.state.activeKey === key) { key = null; } this.setState({ activeKey: key }); }; PanelGroup.prototype.render = function render() { var _this = this; var _props = this.props; var accordion = _props.accordion; var propsActiveKey = _props.activeKey; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['accordion', 'activeKey', 'className', 'children']); var _splitBsPropsAndOmit = _utilsBootstrapUtils.splitBsPropsAndOmit(props, ['defaultActiveKey', 'onSelect']); var bsProps = _splitBsPropsAndOmit[0]; var elementProps = _splitBsPropsAndOmit[1]; var activeKey = undefined; if (accordion) { activeKey = propsActiveKey != null ? propsActiveKey : this.state.activeKey; elementProps.role = elementProps.role || 'tablist'; } var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement( 'div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), _utilsValidComponentChildren2['default'].map(children, function (child) { var childProps = { bsStyle: child.props.bsStyle || bsProps.bsStyle }; if (accordion) { _Object$assign(childProps, { headerRole: 'tab', panelRole: 'tabpanel', collapsible: true, expanded: child.props.eventKey === activeKey, onSelect: _utilsCreateChainedFunction2['default'](_this.handleSelect, child.props.onSelect) }); } return _react.cloneElement(child, childProps); }) ); }; return PanelGroup; })(_react2['default'].Component); PanelGroup.propTypes = propTypes; PanelGroup.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('panel-group', PanelGroup); module.exports = exports['default']; /***/ }, /* 32 */ /***/ function(module, exports) { "use strict"; exports["default"] = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; exports.__esModule = true; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { // TODO: The publicly exposed parts of this should be in lib/BootstrapUtils. 'use strict'; var _extends = __webpack_require__(20)['default']; var _Object$entries = __webpack_require__(35)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports.prefix = prefix; exports.getClassSet = getClassSet; exports.splitBsProps = splitBsProps; exports.splitBsPropsAndOmit = splitBsPropsAndOmit; exports.addStyle = addStyle; var _invariant = __webpack_require__(40); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(30); var _StyleConfig = __webpack_require__(41); function curry(fn) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var last = args[args.length - 1]; if (typeof last === 'function') { return fn.apply(undefined, args); } return function (Component) { return fn.apply(undefined, args.concat([Component])); }; }; } function prefix(props, variant) { !(props.bsClass != null) ? true ? _invariant2['default'](false, 'A `bsClass` prop is required for this component') : _invariant2['default'](false) : undefined; return props.bsClass + (variant ? '-' + variant : ''); } var bsClass = curry(function (defaultClass, Component) { var propTypes = Component.propTypes || (Component.propTypes = {}); var defaultProps = Component.defaultProps || (Component.defaultProps = {}); propTypes.bsClass = _react.PropTypes.string; defaultProps.bsClass = defaultClass; return Component; }); exports.bsClass = bsClass; var bsStyles = curry(function (styles, defaultStyle, Component) { if (typeof defaultStyle !== 'string') { Component = defaultStyle; defaultStyle = undefined; } var existing = Component.STYLES || []; var propTypes = Component.propTypes || {}; styles.forEach(function (style) { if (existing.indexOf(style) === -1) { existing.push(style); } }); var propType = _react.PropTypes.oneOf(existing); // expose the values on the propType function for documentation Component.STYLES = propType._values = existing; Component.propTypes = _extends({}, propTypes, { bsStyle: propType }); if (defaultStyle !== undefined) { var defaultProps = Component.defaultProps || (Component.defaultProps = {}); defaultProps.bsStyle = defaultStyle; } return Component; }); exports.bsStyles = bsStyles; var bsSizes = curry(function (sizes, defaultSize, Component) { if (typeof defaultSize !== 'string') { Component = defaultSize; defaultSize = undefined; } var existing = Component.SIZES || []; var propTypes = Component.propTypes || {}; sizes.forEach(function (size) { if (existing.indexOf(size) === -1) { existing.push(size); } }); var values = []; existing.forEach(function (size) { var mappedSize = _StyleConfig.SIZE_MAP[size]; if (mappedSize && mappedSize !== size) { values.push(mappedSize); } values.push(size); }); var propType = _react.PropTypes.oneOf(values); propType._values = values; // expose the values on the propType function for documentation Component.SIZES = existing; Component.propTypes = _extends({}, propTypes, { bsSize: propType }); if (defaultSize !== undefined) { if (!Component.defaultProps) { Component.defaultProps = {}; } Component.defaultProps.bsSize = defaultSize; } return Component; }); exports.bsSizes = bsSizes; function getClassSet(props) { var _classes; var classes = (_classes = {}, _classes[prefix(props)] = true, _classes); if (props.bsSize) { var bsSize = _StyleConfig.SIZE_MAP[props.bsSize] || props.bsSize; classes[prefix(props, bsSize)] = true; } if (props.bsStyle) { classes[prefix(props, props.bsStyle)] = true; } return classes; } function getBsProps(props) { return { bsClass: props.bsClass, bsSize: props.bsSize, bsStyle: props.bsStyle, bsRole: props.bsRole }; } function isBsProp(propName) { return propName === 'bsClass' || propName === 'bsSize' || propName === 'bsStyle' || propName === 'bsRole'; } function splitBsProps(props) { var elementProps = {}; _Object$entries(props).forEach(function (_ref) { var propName = _ref[0]; var propValue = _ref[1]; if (!isBsProp(propName)) { elementProps[propName] = propValue; } }); return [getBsProps(props), elementProps]; } function splitBsPropsAndOmit(props, omittedPropNames) { var isOmittedProp = {}; omittedPropNames.forEach(function (propName) { isOmittedProp[propName] = true; }); var elementProps = {}; _Object$entries(props).forEach(function (_ref2) { var propName = _ref2[0]; var propValue = _ref2[1]; if (!isBsProp(propName) && !isOmittedProp[propName]) { elementProps[propName] = propValue; } }); return [getBsProps(props), elementProps]; } /** * Add a style variant to a Component. Mutates the propTypes of the component * in order to validate the new variant. */ function addStyle(Component) { for (var _len2 = arguments.length, styleVariant = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { styleVariant[_key2 - 1] = arguments[_key2]; } bsStyles(styleVariant, Component); } var _curry = curry; exports._curry = _curry; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(36), __esModule: true }; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(37); module.exports = __webpack_require__(13).Object.entries; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { // http://goo.gl/XkBrjD var $export = __webpack_require__(11) , $entries = __webpack_require__(38)(true); $export($export.S, 'Object', { entries: function entries(it){ return $entries(it); } }); /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(7) , toIObject = __webpack_require__(39) , isEnum = $.isEnum; module.exports = function(isEntries){ return function(it){ var O = toIObject(it) , keys = $.getKeys(O) , length = keys.length , i = 0 , result = [] , key; while(length > i)if(isEnum.call(O, key = keys[i++])){ result.push(isEntries ? [key, O[key]] : O[key]); } return result; }; }; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(27) , defined = __webpack_require__(26); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (true) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }, /* 41 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; var Size = { LARGE: 'large', SMALL: 'small', XSMALL: 'xsmall' }; exports.Size = Size; var SIZE_MAP = { large: 'lg', medium: 'md', small: 'sm', xsmall: 'xs', lg: 'lg', md: 'md', sm: 'sm', xs: 'xs' }; exports.SIZE_MAP = SIZE_MAP; var DEVICE_SIZES = ['lg', 'md', 'sm', 'xs']; exports.DEVICE_SIZES = DEVICE_SIZES; var State = { SUCCESS: 'success', WARNING: 'warning', DANGER: 'danger', INFO: 'info' }; exports.State = State; var Style = { DEFAULT: 'default', PRIMARY: 'primary', LINK: 'link', INVERSE: 'inverse' }; exports.Style = Style; /***/ }, /* 42 */ /***/ function(module, exports) { /** * Safe chained function * * Will only create a new function if needed, * otherwise will pass back existing functions or null. * * @param {function} functions to chain * @returns {function|null} */ 'use strict'; exports.__esModule = true; function createChainedFunction() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } return funcs.filter(function (f) { return f != null; }).reduce(function (acc, f) { if (typeof f !== 'function') { throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.'); } if (acc === null) { return f; } return function chainedFunction() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } acc.apply(this, args); f.apply(this, args); }; }, null); } exports['default'] = createChainedFunction; module.exports = exports['default']; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { // TODO: This module should be ElementChildren, and should use named exports. 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); /** * Iterates through children that are typically specified as `props.children`, * but only maps over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @return {object} Object containing the ordered map of results. */ function map(children, func, context) { var index = 0; return _react2['default'].Children.map(children, function (child) { if (!_react2['default'].isValidElement(child)) { return child; } return func.call(context, child, index++); }); } /** * Iterates through children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for context. */ function forEach(children, func, context) { var index = 0; _react2['default'].Children.forEach(children, function (child) { if (!_react2['default'].isValidElement(child)) { return; } func.call(context, child, index++); }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function count(children) { var result = 0; _react2['default'].Children.forEach(children, function (child) { if (!_react2['default'].isValidElement(child)) { return; } ++result; }); return result; } /** * Finds children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @returns {array} of children that meet the func return statement */ function filter(children, func, context) { var index = 0; var result = []; _react2['default'].Children.forEach(children, function (child) { if (!_react2['default'].isValidElement(child)) { return; } if (func.call(context, child, index++)) { result.push(child); } }); return result; } function find(children, func, context) { var index = 0; var result = undefined; _react2['default'].Children.forEach(children, function (child) { if (result) { return; } if (!_react2['default'].isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = child; } }); return result; } function every(children, func, context) { var index = 0; var result = true; _react2['default'].Children.forEach(children, function (child) { if (!result) { return; } if (!_react2['default'].isValidElement(child)) { return; } if (!func.call(context, child, index++)) { result = false; } }); return result; } function some(children, func, context) { var index = 0; var result = false; _react2['default'].Children.forEach(children, function (child) { if (result) { return; } if (!_react2['default'].isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = true; } }); return result; } function toArray(children) { var result = []; _react2['default'].Children.forEach(children, function (child) { if (!_react2['default'].isValidElement(child)) { return; } result.push(child); }); return result; } exports['default'] = { map: map, forEach: forEach, count: count, find: find, filter: filter, every: every, some: some, toArray: toArray }; module.exports = exports['default']; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _Object$values = __webpack_require__(45)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var propTypes = { onDismiss: _react2['default'].PropTypes.func, closeLabel: _react2['default'].PropTypes.string }; var defaultProps = { closeLabel: 'Close alert' }; var Alert = (function (_React$Component) { _inherits(Alert, _React$Component); function Alert() { _classCallCheck(this, Alert); _React$Component.apply(this, arguments); } Alert.prototype.renderDismissButton = function renderDismissButton(onDismiss) { return _react2['default'].createElement( 'button', { type: 'button', className: 'close', onClick: onDismiss, 'aria-hidden': 'true', tabIndex: '-1' }, _react2['default'].createElement( 'span', null, '×' ) ); }; Alert.prototype.renderSrOnlyDismissButton = function renderSrOnlyDismissButton(onDismiss, closeLabel) { return _react2['default'].createElement( 'button', { type: 'button', className: 'close sr-only', onClick: onDismiss }, closeLabel ); }; Alert.prototype.render = function render() { var _extends2; var _props = this.props; var onDismiss = _props.onDismiss; var closeLabel = _props.closeLabel; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['onDismiss', 'closeLabel', 'className', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var dismissable = !!onDismiss; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'dismissable')] = dismissable, _extends2)); return _react2['default'].createElement( 'div', _extends({}, elementProps, { role: 'alert', className: _classnames2['default'](className, classes) }), dismissable && this.renderDismissButton(onDismiss), children, dismissable && this.renderSrOnlyDismissButton(onDismiss, closeLabel) ); }; return Alert; })(_react2['default'].Component); Alert.propTypes = propTypes; Alert.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsStyles(_Object$values(_utilsStyleConfig.State), _utilsStyleConfig.State.INFO, _utilsBootstrapUtils.bsClass('alert', Alert)); module.exports = exports['default']; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(46), __esModule: true }; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(47); module.exports = __webpack_require__(13).Object.values; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { // http://goo.gl/XkBrjD var $export = __webpack_require__(11) , $values = __webpack_require__(38)(false); $export($export.S, 'Object', { values: function values(it){ return $values(it); } }); /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); // TODO: `pullRight` doesn't belong here. There's no special handling here. var propTypes = { pullRight: _react2['default'].PropTypes.bool }; var defaultProps = { pullRight: false }; var Badge = (function (_React$Component) { _inherits(Badge, _React$Component); function Badge() { _classCallCheck(this, Badge); _React$Component.apply(this, arguments); } Badge.prototype.hasContent = function hasContent(children) { var result = false; _react2['default'].Children.forEach(children, function (child) { if (result) { return; } if (child || child === 0) { result = true; } }); return result; }; Badge.prototype.render = function render() { var _props = this.props; var pullRight = _props.pullRight; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['pullRight', 'className', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), { 'pull-right': pullRight, // Hack for collapsing on IE8. hidden: !this.hasContent(children) }); return _react2['default'].createElement( 'span', _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), children ); }; return Badge; })(_react2['default'].Component); Badge.propTypes = propTypes; Badge.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('badge', Badge); module.exports = exports['default']; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _BreadcrumbItem = __webpack_require__(50); var _BreadcrumbItem2 = _interopRequireDefault(_BreadcrumbItem); var _utilsBootstrapUtils = __webpack_require__(34); var Breadcrumb = (function (_React$Component) { _inherits(Breadcrumb, _React$Component); function Breadcrumb() { _classCallCheck(this, Breadcrumb); _React$Component.apply(this, arguments); } Breadcrumb.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('ol', _extends({}, elementProps, { role: 'navigation', 'aria-label': 'breadcrumbs', className: _classnames2['default'](className, classes) })); }; return Breadcrumb; })(_react2['default'].Component); Breadcrumb.Item = _BreadcrumbItem2['default']; exports['default'] = _utilsBootstrapUtils.bsClass('breadcrumb', Breadcrumb); module.exports = exports['default']; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _SafeAnchor = __webpack_require__(51); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var propTypes = { /** * If set to true, renders `span` instead of `a` */ active: _react2['default'].PropTypes.bool, /** * `href` attribute for the inner `a` element */ href: _react2['default'].PropTypes.string, /** * `title` attribute for the inner `a` element */ title: _react2['default'].PropTypes.node, /** * `target` attribute for the inner `a` element */ target: _react2['default'].PropTypes.string }; var defaultProps = { active: false }; var BreadcrumbItem = (function (_React$Component) { _inherits(BreadcrumbItem, _React$Component); function BreadcrumbItem() { _classCallCheck(this, BreadcrumbItem); _React$Component.apply(this, arguments); } BreadcrumbItem.prototype.render = function render() { var _props = this.props; var active = _props.active; var href = _props.href; var title = _props.title; var target = _props.target; var className = _props.className; var props = _objectWithoutProperties(_props, ['active', 'href', 'title', 'target', 'className']); // Don't try to render these props on non-active <span>. var linkProps = { href: href, title: title, target: target }; return _react2['default'].createElement( 'li', { className: _classnames2['default'](className, { active: active }) }, active ? _react2['default'].createElement('span', props) : _react2['default'].createElement(_SafeAnchor2['default'], _extends({}, props, linkProps)) ); }; return BreadcrumbItem; })(_react2['default'].Component); BreadcrumbItem.propTypes = propTypes; BreadcrumbItem.defaultProps = defaultProps; exports['default'] = BreadcrumbItem; module.exports = exports['default']; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var propTypes = { href: _react2['default'].PropTypes.string, onClick: _react2['default'].PropTypes.func, disabled: _react2['default'].PropTypes.bool, role: _react2['default'].PropTypes.string, tabIndex: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), /** * this is sort of silly but needed for Button */ componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { componentClass: 'a' }; function isTrivialHref(href) { return !href || href.trim() === '#'; } /** * There are situations due to browser quirks or Bootstrap CSS where * an anchor tag is needed, when semantically a button tag is the * better choice. SafeAnchor ensures that when an anchor is used like a * button its accessible. It also emulates input `disabled` behavior for * links, which is usually desirable for Buttons, NavItems, MenuItems, etc. */ var SafeAnchor = (function (_React$Component) { _inherits(SafeAnchor, _React$Component); function SafeAnchor(props, context) { _classCallCheck(this, SafeAnchor); _React$Component.call(this, props, context); this.handleClick = this.handleClick.bind(this); } SafeAnchor.prototype.handleClick = function handleClick(event) { var _props = this.props; var disabled = _props.disabled; var href = _props.href; var onClick = _props.onClick; if (disabled || isTrivialHref(href)) { event.preventDefault(); } if (disabled) { event.stopPropagation(); return; } if (onClick) { onClick(event); } }; SafeAnchor.prototype.render = function render() { var _props2 = this.props; var Component = _props2.componentClass; var disabled = _props2.disabled; var props = _objectWithoutProperties(_props2, ['componentClass', 'disabled']); if (isTrivialHref(props.href)) { props.role = props.role || 'button'; // we want to make sure there is a href attribute on the node // otherwise, the cursor incorrectly styled (except with role='button') props.href = props.href || ''; } if (disabled) { props.tabIndex = -1; props.style = _extends({ pointerEvents: 'none' }, props.style); } return _react2['default'].createElement(Component, _extends({}, props, { onClick: this.handleClick })); }; return SafeAnchor; })(_react2['default'].Component); SafeAnchor.propTypes = propTypes; SafeAnchor.defaultProps = defaultProps; exports['default'] = SafeAnchor; module.exports = exports['default']; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _common = __webpack_require__(53); /** * Checks whether a prop provides a type of element. * * The type of element can be provided in two forms: * - tag name (string) * - a return value of React.createClass(...) * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ function validate(props, propName, componentName) { var errBeginning = _common.errMsg(props, propName, componentName, '. Expected an Element `type`'); if (typeof props[propName] !== 'function') { if (_react2['default'].isValidElement(props[propName])) { return new Error(errBeginning + ', not an actual Element'); } if (typeof props[propName] !== 'string') { return new Error(errBeginning + ' such as a tag name or return value of React.createClass(...)'); } } } exports['default'] = _common.createChainableTypeChecker(validate); module.exports = exports['default']; /***/ }, /* 53 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.errMsg = errMsg; exports.createChainableTypeChecker = createChainableTypeChecker; function errMsg(props, propName, componentName, msgContinuation) { return 'Invalid prop \'' + propName + '\' of value \'' + props[propName] + '\'' + (' supplied to \'' + componentName + '\'' + msgContinuation); } /** * Create chain-able isRequired validator * * Largely copied directly from: * https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94 */ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName) { componentName = componentName || '<<anonymous>>'; if (props[propName] == null) { if (isRequired) { return new Error('Required prop \'' + propName + '\' was not specified in \'' + componentName + '\'.'); } } else { return validate(props, propName, componentName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _Object$values = __webpack_require__(45)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var _SafeAnchor = __webpack_require__(51); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var propTypes = { active: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, block: _react2['default'].PropTypes.bool, onClick: _react2['default'].PropTypes.func, componentClass: _reactPropTypesLibElementType2['default'], href: _react2['default'].PropTypes.string, /** * Defines HTML button type attribute * @defaultValue 'button' */ type: _react2['default'].PropTypes.oneOf(['button', 'reset', 'submit']) }; var defaultProps = { active: false, block: false, disabled: false }; var Button = (function (_React$Component) { _inherits(Button, _React$Component); function Button() { _classCallCheck(this, Button); _React$Component.apply(this, arguments); } Button.prototype.renderAnchor = function renderAnchor(elementProps, className) { return _react2['default'].createElement(_SafeAnchor2['default'], _extends({}, elementProps, { className: _classnames2['default'](className, elementProps.disabled && 'disabled') })); }; Button.prototype.renderButton = function renderButton(_ref, className) { var componentClass = _ref.componentClass; var elementProps = _objectWithoutProperties(_ref, ['componentClass']); var Component = componentClass || 'button'; return _react2['default'].createElement(Component, _extends({}, elementProps, { type: elementProps.type || 'button', className: className })); }; Button.prototype.render = function render() { var _extends2; var _props = this.props; var active = _props.active; var block = _props.block; var className = _props.className; var props = _objectWithoutProperties(_props, ['active', 'block', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = { active: active }, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'block')] = block, _extends2)); var fullClassName = _classnames2['default'](className, classes); if (elementProps.href) { return this.renderAnchor(elementProps, fullClassName); } return this.renderButton(elementProps, fullClassName); }; return Button; })(_react2['default'].Component); Button.propTypes = propTypes; Button.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('btn', _utilsBootstrapUtils.bsSizes([_utilsStyleConfig.Size.LARGE, _utilsStyleConfig.Size.SMALL, _utilsStyleConfig.Size.XSMALL], _utilsBootstrapUtils.bsStyles([].concat(_Object$values(_utilsStyleConfig.State), [_utilsStyleConfig.Style.DEFAULT, _utilsStyleConfig.Style.PRIMARY, _utilsStyleConfig.Style.LINK]), _utilsStyleConfig.Style.DEFAULT, Button))); module.exports = exports['default']; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibAll = __webpack_require__(56); var _reactPropTypesLibAll2 = _interopRequireDefault(_reactPropTypesLibAll); var _Button = __webpack_require__(54); var _Button2 = _interopRequireDefault(_Button); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { vertical: _react2['default'].PropTypes.bool, justified: _react2['default'].PropTypes.bool, /** * Display block buttons; only useful when used with the "vertical" prop. * @type {bool} */ block: _reactPropTypesLibAll2['default'](_react2['default'].PropTypes.bool, function (_ref) { var block = _ref.block; var vertical = _ref.vertical; return block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null; }) }; var defaultProps = { block: false, justified: false, vertical: false }; var ButtonGroup = (function (_React$Component) { _inherits(ButtonGroup, _React$Component); function ButtonGroup() { _classCallCheck(this, ButtonGroup); _React$Component.apply(this, arguments); } ButtonGroup.prototype.render = function render() { var _extends2; var _props = this.props; var block = _props.block; var justified = _props.justified; var vertical = _props.vertical; var className = _props.className; var props = _objectWithoutProperties(_props, ['block', 'justified', 'vertical', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[_utilsBootstrapUtils.prefix(bsProps)] = !vertical, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'vertical')] = vertical, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'justified')] = justified, _extends2[_utilsBootstrapUtils.prefix(_Button2['default'].defaultProps, 'block')] = block, _extends2)); return _react2['default'].createElement('div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return ButtonGroup; })(_react2['default'].Component); ButtonGroup.propTypes = propTypes; ButtonGroup.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('btn-group', ButtonGroup); module.exports = exports['default']; // this is annoying, since the class is `btn-block` not `btn-group-block` /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = all; var _common = __webpack_require__(53); function all() { for (var _len = arguments.length, propTypes = Array(_len), _key = 0; _key < _len; _key++) { propTypes[_key] = arguments[_key]; } if (propTypes === undefined) { throw new Error('No validations provided'); } if (propTypes.some(function (propType) { return typeof propType !== 'function'; })) { throw new Error('Invalid arguments, must be functions'); } if (propTypes.length === 0) { throw new Error('No validations provided'); } function validate(props, propName, componentName) { for (var i = 0; i < propTypes.length; i++) { var result = propTypes[i](props, propName, componentName); if (result !== undefined && result !== null) { return result; } } } return _common.createChainableTypeChecker(validate); } module.exports = exports['default']; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Button = __webpack_require__(54); var _Button2 = _interopRequireDefault(_Button); var _utilsBootstrapUtils = __webpack_require__(34); var ButtonToolbar = (function (_React$Component) { _inherits(ButtonToolbar, _React$Component); function ButtonToolbar() { _classCallCheck(this, ButtonToolbar); _React$Component.apply(this, arguments); } ButtonToolbar.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('div', _extends({}, elementProps, { role: 'toolbar', className: _classnames2['default'](className, classes) })); }; return ButtonToolbar; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('btn-toolbar', _utilsBootstrapUtils.bsSizes(_Button2['default'].SIZES, ButtonToolbar)); module.exports = exports['default']; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _CarouselCaption = __webpack_require__(59); var _CarouselCaption2 = _interopRequireDefault(_CarouselCaption); var _CarouselItem = __webpack_require__(60); var _CarouselItem2 = _interopRequireDefault(_CarouselItem); var _Glyphicon = __webpack_require__(63); var _Glyphicon2 = _interopRequireDefault(_Glyphicon); var _SafeAnchor = __webpack_require__(51); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); // TODO: `slide` should be `animate`. // TODO: Use uncontrollable. var propTypes = { slide: _react2['default'].PropTypes.bool, indicators: _react2['default'].PropTypes.bool, interval: _react2['default'].PropTypes.number, controls: _react2['default'].PropTypes.bool, pauseOnHover: _react2['default'].PropTypes.bool, wrap: _react2['default'].PropTypes.bool, /** * Callback fired when the active item changes. * * ```js * (eventKey: any) => any | (eventKey: any, event: Object) => any * ``` * * If this callback takes two or more arguments, the second argument will * be a persisted event object with `direction` set to the direction of the * transition. */ onSelect: _react2['default'].PropTypes.func, onSlideEnd: _react2['default'].PropTypes.func, activeIndex: _react2['default'].PropTypes.number, defaultActiveIndex: _react2['default'].PropTypes.number, direction: _react2['default'].PropTypes.oneOf(['prev', 'next']), prevIcon: _react2['default'].PropTypes.node, nextIcon: _react2['default'].PropTypes.node }; var defaultProps = { slide: true, interval: 5000, pauseOnHover: true, wrap: true, indicators: true, controls: true, prevIcon: _react2['default'].createElement(_Glyphicon2['default'], { glyph: 'chevron-left' }), nextIcon: _react2['default'].createElement(_Glyphicon2['default'], { glyph: 'chevron-right' }) }; var Carousel = (function (_React$Component) { _inherits(Carousel, _React$Component); function Carousel(props, context) { _classCallCheck(this, Carousel); _React$Component.call(this, props, context); this.handleMouseOver = this.handleMouseOver.bind(this); this.handleMouseOut = this.handleMouseOut.bind(this); this.handlePrev = this.handlePrev.bind(this); this.handleNext = this.handleNext.bind(this); this.handleItemAnimateOutEnd = this.handleItemAnimateOutEnd.bind(this); var defaultActiveIndex = props.defaultActiveIndex; this.state = { activeIndex: defaultActiveIndex != null ? defaultActiveIndex : 0, previousActiveIndex: null, direction: null }; this.isUnmounted = false; } Carousel.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var activeIndex = this.getActiveIndex(); if (nextProps.activeIndex != null && nextProps.activeIndex !== activeIndex) { clearTimeout(this.timeout); this.setState({ previousActiveIndex: activeIndex, direction: nextProps.direction != null ? nextProps.direction : this.getDirection(activeIndex, nextProps.activeIndex) }); } }; Carousel.prototype.componentDidMount = function componentDidMount() { this.waitForNext(); }; Carousel.prototype.componentWillUnmount = function componentWillUnmount() { clearTimeout(this.timeout); this.isUnmounted = true; }; Carousel.prototype.handleMouseOver = function handleMouseOver() { if (this.props.pauseOnHover) { this.pause(); } }; Carousel.prototype.handleMouseOut = function handleMouseOut() { if (this.isPaused) { this.play(); } }; Carousel.prototype.handlePrev = function handlePrev(e) { var index = this.getActiveIndex() - 1; if (index < 0) { if (!this.props.wrap) { return; } index = _utilsValidComponentChildren2['default'].count(this.props.children) - 1; } this.select(index, e, 'prev'); }; Carousel.prototype.handleNext = function handleNext(e) { var index = this.getActiveIndex() + 1; var count = _utilsValidComponentChildren2['default'].count(this.props.children); if (index > count - 1) { if (!this.props.wrap) { return; } index = 0; } this.select(index, e, 'next'); }; Carousel.prototype.handleItemAnimateOutEnd = function handleItemAnimateOutEnd() { var _this = this; this.setState({ previousActiveIndex: null, direction: null }, function () { _this.waitForNext(); if (_this.props.onSlideEnd) { _this.props.onSlideEnd(); } }); }; Carousel.prototype.getActiveIndex = function getActiveIndex() { var activeIndexProp = this.props.activeIndex; return activeIndexProp != null ? activeIndexProp : this.state.activeIndex; }; Carousel.prototype.getDirection = function getDirection(prevIndex, index) { if (prevIndex === index) { return null; } return prevIndex > index ? 'prev' : 'next'; }; Carousel.prototype.select = function select(index, e, direction) { clearTimeout(this.timeout); // TODO: Is this necessary? Seems like the only risk is if the component // unmounts while handleItemAnimateOutEnd fires. if (this.isUnmounted) { return; } var previousActiveIndex = this.getActiveIndex(); direction = direction || this.getDirection(previousActiveIndex, index); var onSelect = this.props.onSelect; if (onSelect) { if (onSelect.length > 1) { // React SyntheticEvents are pooled, so we need to remove this event // from the pool to add a custom property. To avoid unnecessarily // removing objects from the pool, only do this when the listener // actually wants the event. if (e) { e.persist(); e.direction = direction; } else { e = { direction: direction }; } onSelect(index, e); } else { onSelect(index); } } if (this.props.activeIndex == null && index !== previousActiveIndex) { if (this.state.previousActiveIndex != null) { // If currently animating don't activate the new index. // TODO: look into queueing this canceled call and // animating after the current animation has ended. return; } this.setState({ activeIndex: index, previousActiveIndex: previousActiveIndex, direction: direction }); } }; Carousel.prototype.waitForNext = function waitForNext() { var _props = this.props; var slide = _props.slide; var interval = _props.interval; var activeIndexProp = _props.activeIndex; if (!this.isPaused && slide && interval && activeIndexProp == null) { this.timeout = setTimeout(this.handleNext, interval); } }; // This might be a public API. Carousel.prototype.pause = function pause() { this.isPaused = true; clearTimeout(this.timeout); }; // This might be a public API. Carousel.prototype.play = function play() { this.isPaused = false; this.waitForNext(); }; Carousel.prototype.renderIndicators = function renderIndicators(children, activeIndex, bsProps) { var _this2 = this; var indicators = []; _utilsValidComponentChildren2['default'].forEach(children, function (child, index) { indicators.push(_react2['default'].createElement('li', { key: index, className: index === activeIndex ? 'active' : null, onClick: function (e) { return _this2.select(index, e); } }), // Force whitespace between indicator elements. Bootstrap requires // this for correct spacing of elements. ' '); }); return _react2['default'].createElement( 'ol', { className: _utilsBootstrapUtils.prefix(bsProps, 'indicators') }, indicators ); }; Carousel.prototype.renderControls = function renderControls(wrap, children, activeIndex, prevIcon, nextIcon, bsProps) { var controlClassName = _utilsBootstrapUtils.prefix(bsProps, 'control'); var count = _utilsValidComponentChildren2['default'].count(children); return [(wrap || activeIndex !== 0) && _react2['default'].createElement( _SafeAnchor2['default'], { key: 'prev', className: _classnames2['default'](controlClassName, 'left'), onClick: this.handlePrev }, prevIcon ), (wrap || activeIndex !== count - 1) && _react2['default'].createElement( _SafeAnchor2['default'], { key: 'next', className: _classnames2['default'](controlClassName, 'right'), onClick: this.handleNext }, nextIcon )]; }; Carousel.prototype.render = function render() { var _this3 = this; var _props2 = this.props; var slide = _props2.slide; var indicators = _props2.indicators; var controls = _props2.controls; var wrap = _props2.wrap; var prevIcon = _props2.prevIcon; var nextIcon = _props2.nextIcon; var className = _props2.className; var children = _props2.children; var props = _objectWithoutProperties(_props2, ['slide', 'indicators', 'controls', 'wrap', 'prevIcon', 'nextIcon', 'className', 'children']); var _state = this.state; var previousActiveIndex = _state.previousActiveIndex; var direction = _state.direction; var _splitBsPropsAndOmit = _utilsBootstrapUtils.splitBsPropsAndOmit(props, ['interval', 'pauseOnHover', 'onSelect', 'onSlideEnd', 'activeIndex', // Accessed via this.getActiveIndex(). 'defaultActiveIndex', 'direction']); var bsProps = _splitBsPropsAndOmit[0]; var elementProps = _splitBsPropsAndOmit[1]; var activeIndex = this.getActiveIndex(); var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), { slide: slide }); return _react2['default'].createElement( 'div', _extends({}, elementProps, { className: _classnames2['default'](className, classes), onMouseOver: this.handleMouseOver, onMouseOut: this.handleMouseOut }), indicators && this.renderIndicators(children, activeIndex, bsProps), _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils.prefix(bsProps, 'inner') }, _utilsValidComponentChildren2['default'].map(children, function (child, index) { var active = index === activeIndex; var previousActive = slide && index === previousActiveIndex; return _react.cloneElement(child, { active: active, index: index, animateOut: previousActive, animateIn: active && previousActiveIndex != null && slide, direction: direction, onAnimateOutEnd: previousActive ? _this3.handleItemAnimateOutEnd : null }); }) ), controls && this.renderControls(wrap, children, activeIndex, prevIcon, nextIcon, bsProps) ); }; return Carousel; })(_react2['default'].Component); Carousel.propTypes = propTypes; Carousel.defaultProps = defaultProps; Carousel.Caption = _CarouselCaption2['default']; Carousel.Item = _CarouselItem2['default']; exports['default'] = _utilsBootstrapUtils.bsClass('carousel', Carousel); module.exports = exports['default']; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { componentClass: 'div' }; var CarouselCaption = (function (_React$Component) { _inherits(CarouselCaption, _React$Component); function CarouselCaption() { _classCallCheck(this, CarouselCaption); _React$Component.apply(this, arguments); } CarouselCaption.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return CarouselCaption; })(_react2['default'].Component); CarouselCaption.propTypes = propTypes; CarouselCaption.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('carousel-caption', CarouselCaption); module.exports = exports['default']; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _utilsTransitionEvents = __webpack_require__(62); var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents); // TODO: This should use a timeout instead of TransitionEvents, or else just // not wait until transition end to trigger continuing animations. var propTypes = { direction: _react2['default'].PropTypes.oneOf(['prev', 'next']), onAnimateOutEnd: _react2['default'].PropTypes.func, active: _react2['default'].PropTypes.bool, animateIn: _react2['default'].PropTypes.bool, animateOut: _react2['default'].PropTypes.bool, index: _react2['default'].PropTypes.number }; var defaultProps = { active: false, animateIn: false, animateOut: false }; var CarouselItem = (function (_React$Component) { _inherits(CarouselItem, _React$Component); function CarouselItem(props, context) { _classCallCheck(this, CarouselItem); _React$Component.call(this, props, context); this.handleAnimateOutEnd = this.handleAnimateOutEnd.bind(this); this.state = { direction: null }; this.isUnmounted = false; } CarouselItem.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }; CarouselItem.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { var _this = this; var active = this.props.active; var prevActive = prevProps.active; if (!active && prevActive) { _utilsTransitionEvents2['default'].addEndEventListener(_reactDom2['default'].findDOMNode(this), this.handleAnimateOutEnd); } if (active !== prevActive) { setTimeout(function () { return _this.startAnimation(); }, 20); } }; CarouselItem.prototype.componentWillUnmount = function componentWillUnmount() { this.isUnmounted = true; }; CarouselItem.prototype.handleAnimateOutEnd = function handleAnimateOutEnd() { if (this.isUnmounted) { return; } if (this.props.onAnimateOutEnd) { this.props.onAnimateOutEnd(this.props.index); } }; CarouselItem.prototype.startAnimation = function startAnimation() { if (this.isUnmounted) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }; CarouselItem.prototype.render = function render() { var _props = this.props; var direction = _props.direction; var active = _props.active; var animateIn = _props.animateIn; var animateOut = _props.animateOut; var className = _props.className; var props = _objectWithoutProperties(_props, ['direction', 'active', 'animateIn', 'animateOut', 'className']); delete props.onAnimateOutEnd; delete props.index; var classes = { item: true, active: active && !animateIn || animateOut }; if (direction && active && animateIn) { classes[direction] = true; } if (this.state.direction && (animateIn || animateOut)) { classes[this.state.direction] = true; } return _react2['default'].createElement('div', _extends({}, props, { className: _classnames2['default'](className, classes) })); }; return CarouselItem; })(_react2['default'].Component); CarouselItem.propTypes = propTypes; CarouselItem.defaultProps = defaultProps; exports['default'] = CarouselItem; module.exports = exports['default']; /***/ }, /* 61 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_61__; /***/ }, /* 62 */ /***/ function(module, exports) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This file contains a modified version of: * https://github.com/facebook/react/blob/v0.12.0/src/addons/transitions/ReactTransitionEvents.js * * This source code is licensed under the BSD-style license found here: * https://github.com/facebook/react/blob/v0.12.0/LICENSE * An additional grant of patent rights can be found here: * https://github.com/facebook/react/blob/v0.12.0/PATENTS */ 'use strict'; exports.__esModule = true; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ var EVENT_NAME_MAP = { transitionend: { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'mozTransitionEnd', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd' }, animationend: { 'animation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'mozAnimationEnd', 'OAnimation': 'oAnimationEnd', 'msAnimation': 'MSAnimationEnd' } }; var endEvents = []; function detectEvents() { var testEl = document.createElement('div'); var style = testEl.style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition; } for (var baseEventName in EVENT_NAME_MAP) { // eslint-disable-line guard-for-in var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]); break; } } } } if (canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function addEndEventListener(node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function (endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function removeEndEventListener(node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function (endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; exports['default'] = ReactTransitionEvents; module.exports = exports['default']; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { /** * An icon name. See e.g. http://getbootstrap.com/components/#glyphicons */ glyph: _react2['default'].PropTypes.string.isRequired }; var Glyphicon = (function (_React$Component) { _inherits(Glyphicon, _React$Component); function Glyphicon() { _classCallCheck(this, Glyphicon); _React$Component.apply(this, arguments); } Glyphicon.prototype.render = function render() { var _extends2; var _props = this.props; var glyph = _props.glyph; var className = _props.className; var props = _objectWithoutProperties(_props, ['glyph', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[_utilsBootstrapUtils.prefix(bsProps, glyph)] = true, _extends2)); return _react2['default'].createElement('span', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Glyphicon; })(_react2['default'].Component); Glyphicon.propTypes = propTypes; exports['default'] = _utilsBootstrapUtils.bsClass('glyphicon', Glyphicon); module.exports = exports['default']; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { inline: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, /** * Only valid if `inline` is not set. */ validationState: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Checkbox inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: _react2['default'].PropTypes.func }; var defaultProps = { inline: false, disabled: false }; var Checkbox = (function (_React$Component) { _inherits(Checkbox, _React$Component); function Checkbox() { _classCallCheck(this, Checkbox); _React$Component.apply(this, arguments); } Checkbox.prototype.render = function render() { var _props = this.props; var inline = _props.inline; var disabled = _props.disabled; var validationState = _props.validationState; var inputRef = _props.inputRef; var className = _props.className; var style = _props.style; var children = _props.children; var props = _objectWithoutProperties(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var input = _react2['default'].createElement('input', _extends({}, elementProps, { ref: inputRef, type: 'checkbox', disabled: disabled })); if (inline) { var _classes; var _classes2 = (_classes = {}, _classes[_utilsBootstrapUtils.prefix(bsProps, 'inline')] = true, _classes.disabled = disabled, _classes); // Use a warning here instead of in propTypes to get better-looking // generated documentation. true ? _warning2['default'](!validationState, '`validationState` is ignored on `<Checkbox inline>`. To display ' + 'validation state on an inline checkbox, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : undefined; return _react2['default'].createElement( 'label', { className: _classnames2['default'](className, _classes2), style: style }, input, children ); } var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return _react2['default'].createElement( 'div', { className: _classnames2['default'](className, classes), style: style }, _react2['default'].createElement( 'label', null, input, children ) ); }; return Checkbox; })(_react2['default'].Component); Checkbox.propTypes = propTypes; Checkbox.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('checkbox', Checkbox); module.exports = exports['default']; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = function() {}; if (true) { warning = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCapitalize = __webpack_require__(67); var _utilsCapitalize2 = _interopRequireDefault(_utilsCapitalize); var _utilsStyleConfig = __webpack_require__(41); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'], /** * Apply clearfix * * on Extra small devices Phones * * adds class `visible-xs-block` */ visibleXsBlock: _react2['default'].PropTypes.bool, /** * Apply clearfix * * on Small devices Tablets * * adds class `visible-sm-block` */ visibleSmBlock: _react2['default'].PropTypes.bool, /** * Apply clearfix * * on Medium devices Desktops * * adds class `visible-md-block` */ visibleMdBlock: _react2['default'].PropTypes.bool, /** * Apply clearfix * * on Large devices Desktops * * adds class `visible-lg-block` */ visibleLgBlock: _react2['default'].PropTypes.bool }; var defaultProps = { componentClass: 'div' }; var Clearfix = (function (_React$Component) { _inherits(Clearfix, _React$Component); function Clearfix() { _classCallCheck(this, Clearfix); _React$Component.apply(this, arguments); } Clearfix.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); _utilsStyleConfig.DEVICE_SIZES.forEach(function (size) { var propName = 'visible' + _utilsCapitalize2['default'](size) + 'Block'; if (elementProps[propName]) { classes['visible-' + size + '-block'] = true; } delete elementProps[propName]; }); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Clearfix; })(_react2['default'].Component); Clearfix.propTypes = propTypes; Clearfix.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('clearfix', Clearfix); module.exports = exports['default']; /***/ }, /* 67 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = capitalize; function capitalize(string) { return "" + string.charAt(0).toUpperCase() + string.slice(1); } module.exports = exports["default"]; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { /** * Uses `controlId` from `<FormGroup>` if not explicitly specified. */ htmlFor: _react2['default'].PropTypes.string, srOnly: _react2['default'].PropTypes.bool }; var defaultProps = { srOnly: false }; var contextTypes = { $bs_formGroup: _react2['default'].PropTypes.object }; var ControlLabel = (function (_React$Component) { _inherits(ControlLabel, _React$Component); function ControlLabel() { _classCallCheck(this, ControlLabel); _React$Component.apply(this, arguments); } ControlLabel.prototype.render = function render() { var formGroup = this.context.$bs_formGroup; var controlId = formGroup && formGroup.controlId; var _props = this.props; var _props$htmlFor = _props.htmlFor; var htmlFor = _props$htmlFor === undefined ? controlId : _props$htmlFor; var srOnly = _props.srOnly; var className = _props.className; var props = _objectWithoutProperties(_props, ['htmlFor', 'srOnly', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; true ? _warning2['default'](controlId == null || htmlFor === controlId, '`controlId` is ignored on `<ControlLabel>` when `htmlFor` is specified.') : undefined; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), { 'sr-only': srOnly }); return _react2['default'].createElement('label', _extends({}, elementProps, { htmlFor: htmlFor, className: _classnames2['default'](className, classes) })); }; return ControlLabel; })(_react2['default'].Component); ControlLabel.propTypes = propTypes; ControlLabel.defaultProps = defaultProps; ControlLabel.contextTypes = contextTypes; exports['default'] = _utilsBootstrapUtils.bsClass('control-label', ControlLabel); module.exports = exports['default']; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'], /** * The number of columns you wish to span * * for Extra small devices Phones (<768px) * * class-prefix `col-xs-` */ xs: _react2['default'].PropTypes.number, /** * The number of columns you wish to span * * for Small devices Tablets (≥768px) * * class-prefix `col-sm-` */ sm: _react2['default'].PropTypes.number, /** * The number of columns you wish to span * * for Medium devices Desktops (≥992px) * * class-prefix `col-md-` */ md: _react2['default'].PropTypes.number, /** * The number of columns you wish to span * * for Large devices Desktops (≥1200px) * * class-prefix `col-lg-` */ lg: _react2['default'].PropTypes.number, /** * Hide column * * on Extra small devices Phones * * adds class `hidden-xs` */ xsHidden: _react2['default'].PropTypes.bool, /** * Hide column * * on Small devices Tablets * * adds class `hidden-sm` */ smHidden: _react2['default'].PropTypes.bool, /** * Hide column * * on Medium devices Desktops * * adds class `hidden-md` */ mdHidden: _react2['default'].PropTypes.bool, /** * Hide column * * on Large devices Desktops * * adds class `hidden-lg` */ lgHidden: _react2['default'].PropTypes.bool, /** * Move columns to the right * * for Extra small devices Phones * * class-prefix `col-xs-offset-` */ xsOffset: _react2['default'].PropTypes.number, /** * Move columns to the right * * for Small devices Tablets * * class-prefix `col-sm-offset-` */ smOffset: _react2['default'].PropTypes.number, /** * Move columns to the right * * for Medium devices Desktops * * class-prefix `col-md-offset-` */ mdOffset: _react2['default'].PropTypes.number, /** * Move columns to the right * * for Large devices Desktops * * class-prefix `col-lg-offset-` */ lgOffset: _react2['default'].PropTypes.number, /** * Change the order of grid columns to the right * * for Extra small devices Phones * * class-prefix `col-xs-push-` */ xsPush: _react2['default'].PropTypes.number, /** * Change the order of grid columns to the right * * for Small devices Tablets * * class-prefix `col-sm-push-` */ smPush: _react2['default'].PropTypes.number, /** * Change the order of grid columns to the right * * for Medium devices Desktops * * class-prefix `col-md-push-` */ mdPush: _react2['default'].PropTypes.number, /** * Change the order of grid columns to the right * * for Large devices Desktops * * class-prefix `col-lg-push-` */ lgPush: _react2['default'].PropTypes.number, /** * Change the order of grid columns to the left * * for Extra small devices Phones * * class-prefix `col-xs-pull-` */ xsPull: _react2['default'].PropTypes.number, /** * Change the order of grid columns to the left * * for Small devices Tablets * * class-prefix `col-sm-pull-` */ smPull: _react2['default'].PropTypes.number, /** * Change the order of grid columns to the left * * for Medium devices Desktops * * class-prefix `col-md-pull-` */ mdPull: _react2['default'].PropTypes.number, /** * Change the order of grid columns to the left * * for Large devices Desktops * * class-prefix `col-lg-pull-` */ lgPull: _react2['default'].PropTypes.number }; var defaultProps = { componentClass: 'div' }; var Col = (function (_React$Component) { _inherits(Col, _React$Component); function Col() { _classCallCheck(this, Col); _React$Component.apply(this, arguments); } Col.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = []; _utilsStyleConfig.DEVICE_SIZES.forEach(function (size) { function popProp(propSuffix, modifier) { var propName = '' + size + propSuffix; var propValue = elementProps[propName]; if (propValue != null) { classes.push(_utilsBootstrapUtils.prefix(bsProps, '' + size + modifier + '-' + propValue)); } delete elementProps[propName]; } popProp('', ''); popProp('Offset', '-offset'); popProp('Push', '-push'); popProp('Pull', '-pull'); var hiddenPropName = size + 'Hidden'; if (elementProps[hiddenPropName]) { classes.push('hidden-' + size); } delete elementProps[hiddenPropName]; }); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Col; })(_react2['default'].Component); Col.propTypes = propTypes; Col.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('col', Col); module.exports = exports['default']; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _domHelpersStyle = __webpack_require__(71); var _domHelpersStyle2 = _interopRequireDefault(_domHelpersStyle); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactOverlaysLibTransition = __webpack_require__(79); var _reactOverlaysLibTransition2 = _interopRequireDefault(_reactOverlaysLibTransition); var _utilsCapitalize = __webpack_require__(67); var _utilsCapitalize2 = _interopRequireDefault(_utilsCapitalize); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var MARGINS = { height: ['marginTop', 'marginBottom'], width: ['marginLeft', 'marginRight'] }; // reading a dimension prop will cause the browser to recalculate, // which will let our animations work function triggerBrowserReflow(node) { node.offsetHeight; // eslint-disable-line no-unused-expressions } function getDimensionValue(dimension, elem) { var value = elem['offset' + _utilsCapitalize2['default'](dimension)]; var margins = MARGINS[dimension]; return value + parseInt(_domHelpersStyle2['default'](elem, margins[0]), 10) + parseInt(_domHelpersStyle2['default'](elem, margins[1]), 10); } var propTypes = { /** * Show the component; triggers the expand or collapse animation */ 'in': _react2['default'].PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is collapsed */ unmountOnExit: _react2['default'].PropTypes.bool, /** * Run the expand animation when the component mounts, if it is initially * shown */ transitionAppear: _react2['default'].PropTypes.bool, /** * Duration of the collapse animation in milliseconds, to ensure that * finishing callbacks are fired even if the original browser transition end * events are canceled */ timeout: _react2['default'].PropTypes.number, /** * Callback fired before the component expands */ onEnter: _react2['default'].PropTypes.func, /** * Callback fired after the component starts to expand */ onEntering: _react2['default'].PropTypes.func, /** * Callback fired after the component has expanded */ onEntered: _react2['default'].PropTypes.func, /** * Callback fired before the component collapses */ onExit: _react2['default'].PropTypes.func, /** * Callback fired after the component starts to collapse */ onExiting: _react2['default'].PropTypes.func, /** * Callback fired after the component has collapsed */ onExited: _react2['default'].PropTypes.func, /** * The dimension used when collapsing, or a function that returns the * dimension * * _Note: Bootstrap only partially supports 'width'! * You will need to supply your own CSS animation for the `.width` CSS class._ */ dimension: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.oneOf(['height', 'width']), _react2['default'].PropTypes.func]), /** * Function that returns the height or width of the animating DOM node * * Allows for providing some custom logic for how much the Collapse component * should animate in its specified dimension. Called with the current * dimension prop value and the DOM node. */ getDimensionValue: _react2['default'].PropTypes.func, /** * ARIA role of collapsible element */ role: _react2['default'].PropTypes.string }; var defaultProps = { 'in': false, timeout: 300, unmountOnExit: false, transitionAppear: false, dimension: 'height', getDimensionValue: getDimensionValue }; var Collapse = (function (_React$Component) { _inherits(Collapse, _React$Component); function Collapse(props, context) { _classCallCheck(this, Collapse); _React$Component.call(this, props, context); this.handleEnter = this.handleEnter.bind(this); this.handleEntering = this.handleEntering.bind(this); this.handleEntered = this.handleEntered.bind(this); this.handleExit = this.handleExit.bind(this); this.handleExiting = this.handleExiting.bind(this); } /* -- Expanding -- */ Collapse.prototype.handleEnter = function handleEnter(elem) { var dimension = this._dimension(); elem.style[dimension] = '0'; }; Collapse.prototype.handleEntering = function handleEntering(elem) { var dimension = this._dimension(); elem.style[dimension] = this._getScrollDimensionValue(elem, dimension); }; Collapse.prototype.handleEntered = function handleEntered(elem) { var dimension = this._dimension(); elem.style[dimension] = null; }; /* -- Collapsing -- */ Collapse.prototype.handleExit = function handleExit(elem) { var dimension = this._dimension(); elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px'; }; Collapse.prototype.handleExiting = function handleExiting(elem) { var dimension = this._dimension(); triggerBrowserReflow(elem); elem.style[dimension] = '0'; }; Collapse.prototype._dimension = function _dimension() { return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension; }; // for testing Collapse.prototype._getTransitionInstance = function _getTransitionInstance() { return this.refs.transition; }; Collapse.prototype._getScrollDimensionValue = function _getScrollDimensionValue(elem, dimension) { return elem['scroll' + _utilsCapitalize2['default'](dimension)] + 'px'; }; Collapse.prototype.render = function render() { var _props = this.props; var onEnter = _props.onEnter; var onEntering = _props.onEntering; var onEntered = _props.onEntered; var onExit = _props.onExit; var onExiting = _props.onExiting; var className = _props.className; var props = _objectWithoutProperties(_props, ['onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'className']); delete props.dimension; delete props.getDimensionValue; var handleEnter = _utilsCreateChainedFunction2['default'](this.handleEnter, onEnter); var handleEntering = _utilsCreateChainedFunction2['default'](this.handleEntering, onEntering); var handleEntered = _utilsCreateChainedFunction2['default'](this.handleEntered, onEntered); var handleExit = _utilsCreateChainedFunction2['default'](this.handleExit, onExit); var handleExiting = _utilsCreateChainedFunction2['default'](this.handleExiting, onExiting); var classes = { width: this._dimension() === 'width' }; return _react2['default'].createElement(_reactOverlaysLibTransition2['default'], _extends({ ref: 'transition' }, props, { 'aria-expanded': props.role ? props['in'] : null, className: _classnames2['default'](className, classes), exitedClassName: 'collapse', exitingClassName: 'collapsing', enteredClassName: 'collapse in', enteringClassName: 'collapsing', onEnter: handleEnter, onEntering: handleEntering, onEntered: handleEntered, onExit: handleExit, onExiting: handleExiting })); }; return Collapse; })(_react2['default'].Component); Collapse.propTypes = propTypes; Collapse.defaultProps = defaultProps; exports['default'] = Collapse; module.exports = exports['default']; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var camelize = __webpack_require__(72), hyphenate = __webpack_require__(74), _getComputedStyle = __webpack_require__(76), removeStyle = __webpack_require__(78); var has = Object.prototype.hasOwnProperty; module.exports = function style(node, property, value) { var css = '', props = property; if (typeof property === 'string') { if (value === undefined) return node.style[camelize(property)] || _getComputedStyle(node).getPropertyValue(hyphenate(property));else (props = {})[property] = value; } for (var key in props) if (has.call(props, key)) { !props[key] && props[key] !== 0 ? removeStyle(node, hyphenate(key)) : css += hyphenate(key) + ':' + props[key] + ';'; } node.style.cssText += ';' + css; }; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/camelizeStyleName.js */ 'use strict'; var camelize = __webpack_require__(73); var msPattern = /^-ms-/; module.exports = function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); }; /***/ }, /* 73 */ /***/ function(module, exports) { "use strict"; var rHyphen = /-(.)/g; module.exports = function camelize(string) { return string.replace(rHyphen, function (_, chr) { return chr.toUpperCase(); }); }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js */ "use strict"; var hyphenate = __webpack_require__(75); var msPattern = /^ms-/; module.exports = function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, "-ms-"); }; /***/ }, /* 75 */ /***/ function(module, exports) { 'use strict'; var rUpper = /([A-Z])/g; module.exports = function hyphenate(string) { return string.replace(rUpper, '-$1').toLowerCase(); }; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(77); var _utilCamelizeStyle = __webpack_require__(72); var _utilCamelizeStyle2 = babelHelpers.interopRequireDefault(_utilCamelizeStyle); var rposition = /^(top|right|bottom|left)$/; var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i; module.exports = function _getComputedStyle(node) { if (!node) throw new TypeError('No Element passed to `getComputedStyle()`'); var doc = node.ownerDocument; return 'defaultView' in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : { //ie 8 "magic" from: https://github.com/jquery/jquery/blob/1.11-stable/src/css/curCSS.js#L72 getPropertyValue: function getPropertyValue(prop) { var style = node.style; prop = (0, _utilCamelizeStyle2['default'])(prop); if (prop == 'float') prop = 'styleFloat'; var current = node.currentStyle[prop] || null; if (current == null && style && style[prop]) current = style[prop]; if (rnumnonpx.test(current) && !rposition.test(prop)) { // Remember the original values var left = style.left; var runStyle = node.runtimeStyle; var rsLeft = runStyle && runStyle.left; // Put in the new values to get a computed value out if (rsLeft) runStyle.left = node.currentStyle.left; style.left = prop === 'fontSize' ? '1em' : current; current = style.pixelLeft + 'px'; // Revert the changed values style.left = left; if (rsLeft) runStyle.left = rsLeft; } return current; } }; }; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports === "object") { factory(exports); } else { factory(root.babelHelpers = {}); } })(this, function (global) { var babelHelpers = global; babelHelpers.interopRequireDefault = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; babelHelpers._extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; }) /***/ }, /* 78 */ /***/ function(module, exports) { 'use strict'; module.exports = function removeStyle(node, key) { return 'removeProperty' in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key); }; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.EXITING = exports.ENTERED = exports.ENTERING = exports.EXITED = exports.UNMOUNTED = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _properties = __webpack_require__(80); var _properties2 = _interopRequireDefault(_properties); var _on = __webpack_require__(82); var _on2 = _interopRequireDefault(_on); var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var transitionEndEvent = _properties2.default.end; var UNMOUNTED = exports.UNMOUNTED = 0; var EXITED = exports.EXITED = 1; var ENTERING = exports.ENTERING = 2; var ENTERED = exports.ENTERED = 3; var EXITING = exports.EXITING = 4; /** * The Transition component lets you define and run css transitions with a simple declarative api. * It works similar to React's own [CSSTransitionGroup](http://facebook.github.io/react/docs/animation.html#high-level-api-reactcsstransitiongroup) * but is specifically optimized for transitioning a single child "in" or "out". * * You don't even need to use class based css transitions if you don't want to (but it is easiest). * The extensive set of lifecyle callbacks means you have control over * the transitioning now at each step of the way. */ var Transition = function (_React$Component) { _inherits(Transition, _React$Component); function Transition(props, context) { _classCallCheck(this, Transition); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Transition).call(this, props, context)); var initialStatus = void 0; if (props.in) { // Start enter transition in componentDidMount. initialStatus = props.transitionAppear ? EXITED : ENTERED; } else { initialStatus = props.unmountOnExit ? UNMOUNTED : EXITED; } _this.state = { status: initialStatus }; _this.nextCallback = null; return _this; } _createClass(Transition, [{ key: 'componentDidMount', value: function componentDidMount() { if (this.props.transitionAppear && this.props.in) { this.performEnter(this.props); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.in && this.props.unmountOnExit) { if (this.state.status === UNMOUNTED) { // Start enter transition in componentDidUpdate. this.setState({ status: EXITED }); } } else { this._needsUpdate = true; } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { var status = this.state.status; if (this.props.unmountOnExit && status === EXITED) { // EXITED is always a transitional state to either ENTERING or UNMOUNTED // when using unmountOnExit. if (this.props.in) { this.performEnter(this.props); } else { this.setState({ status: UNMOUNTED }); } return; } // guard ensures we are only responding to prop changes if (this._needsUpdate) { this._needsUpdate = false; if (this.props.in) { if (status === EXITING) { this.performEnter(this.props); } else if (status === EXITED) { this.performEnter(this.props); } // Otherwise we're already entering or entered. } else { if (status === ENTERING || status === ENTERED) { this.performExit(this.props); } // Otherwise we're already exited or exiting. } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.cancelNextCallback(); } }, { key: 'performEnter', value: function performEnter(props) { var _this2 = this; this.cancelNextCallback(); var node = _reactDom2.default.findDOMNode(this); // Not this.props, because we might be about to receive new props. props.onEnter(node); this.safeSetState({ status: ENTERING }, function () { _this2.props.onEntering(node); _this2.onTransitionEnd(node, function () { _this2.safeSetState({ status: ENTERED }, function () { _this2.props.onEntered(node); }); }); }); } }, { key: 'performExit', value: function performExit(props) { var _this3 = this; this.cancelNextCallback(); var node = _reactDom2.default.findDOMNode(this); // Not this.props, because we might be about to receive new props. props.onExit(node); this.safeSetState({ status: EXITING }, function () { _this3.props.onExiting(node); _this3.onTransitionEnd(node, function () { _this3.safeSetState({ status: EXITED }, function () { _this3.props.onExited(node); }); }); }); } }, { key: 'cancelNextCallback', value: function cancelNextCallback() { if (this.nextCallback !== null) { this.nextCallback.cancel(); this.nextCallback = null; } } }, { key: 'safeSetState', value: function safeSetState(nextState, callback) { // This shouldn't be necessary, but there are weird race conditions with // setState callbacks and unmounting in testing, so always make sure that // we can cancel any pending setState callbacks after we unmount. this.setState(nextState, this.setNextCallback(callback)); } }, { key: 'setNextCallback', value: function setNextCallback(callback) { var _this4 = this; var active = true; this.nextCallback = function (event) { if (active) { active = false; _this4.nextCallback = null; callback(event); } }; this.nextCallback.cancel = function () { active = false; }; return this.nextCallback; } }, { key: 'onTransitionEnd', value: function onTransitionEnd(node, handler) { this.setNextCallback(handler); if (node) { (0, _on2.default)(node, transitionEndEvent, this.nextCallback); setTimeout(this.nextCallback, this.props.timeout); } else { setTimeout(this.nextCallback, 0); } } }, { key: 'render', value: function render() { var status = this.state.status; if (status === UNMOUNTED) { return null; } var _props = this.props; var children = _props.children; var className = _props.className; var childProps = _objectWithoutProperties(_props, ['children', 'className']); Object.keys(Transition.propTypes).forEach(function (key) { return delete childProps[key]; }); var transitionClassName = void 0; if (status === EXITED) { transitionClassName = this.props.exitedClassName; } else if (status === ENTERING) { transitionClassName = this.props.enteringClassName; } else if (status === ENTERED) { transitionClassName = this.props.enteredClassName; } else if (status === EXITING) { transitionClassName = this.props.exitingClassName; } var child = _react2.default.Children.only(children); return _react2.default.cloneElement(child, _extends({}, childProps, { className: (0, _classnames2.default)(child.props.className, className, transitionClassName) })); } }]); return Transition; }(_react2.default.Component); Transition.propTypes = { /** * Show the component; triggers the enter or exit animation */ in: _react2.default.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is not shown */ unmountOnExit: _react2.default.PropTypes.bool, /** * Run the enter animation when the component mounts, if it is initially * shown */ transitionAppear: _react2.default.PropTypes.bool, /** * A Timeout for the animation, in milliseconds, to ensure that a node doesn't * transition indefinately if the browser transitionEnd events are * canceled or interrupted. * * By default this is set to a high number (5 seconds) as a failsafe. You should consider * setting this to the duration of your animation (or a bit above it). */ timeout: _react2.default.PropTypes.number, /** * CSS class or classes applied when the component is exited */ exitedClassName: _react2.default.PropTypes.string, /** * CSS class or classes applied while the component is exiting */ exitingClassName: _react2.default.PropTypes.string, /** * CSS class or classes applied when the component is entered */ enteredClassName: _react2.default.PropTypes.string, /** * CSS class or classes applied while the component is entering */ enteringClassName: _react2.default.PropTypes.string, /** * Callback fired before the "entering" classes are applied */ onEnter: _react2.default.PropTypes.func, /** * Callback fired after the "entering" classes are applied */ onEntering: _react2.default.PropTypes.func, /** * Callback fired after the "enter" classes are applied */ onEntered: _react2.default.PropTypes.func, /** * Callback fired before the "exiting" classes are applied */ onExit: _react2.default.PropTypes.func, /** * Callback fired after the "exiting" classes are applied */ onExiting: _react2.default.PropTypes.func, /** * Callback fired after the "exited" classes are applied */ onExited: _react2.default.PropTypes.func }; // Name the function so it is clearer in the documentation function noop() {} Transition.displayName = 'Transition'; Transition.defaultProps = { in: false, unmountOnExit: false, transitionAppear: false, timeout: 5000, onEnter: noop, onEntering: noop, onEntered: noop, onExit: noop, onExiting: noop, onExited: noop }; exports.default = Transition; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(81); var has = Object.prototype.hasOwnProperty, transform = 'transform', transition = {}, transitionTiming, transitionDuration, transitionProperty, transitionDelay; if (canUseDOM) { transition = getTransitionProperties(); transform = transition.prefix + transform; transitionProperty = transition.prefix + 'transition-property'; transitionDuration = transition.prefix + 'transition-duration'; transitionDelay = transition.prefix + 'transition-delay'; transitionTiming = transition.prefix + 'transition-timing-function'; } module.exports = { transform: transform, end: transition.end, property: transitionProperty, timing: transitionTiming, delay: transitionDelay, duration: transitionDuration }; function getTransitionProperties() { var endEvent, prefix = '', transitions = { O: 'otransitionend', Moz: 'transitionend', Webkit: 'webkitTransitionEnd', ms: 'MSTransitionEnd' }; var element = document.createElement('div'); for (var vendor in transitions) if (has.call(transitions, vendor)) { if (element.style[vendor + 'TransitionProperty'] !== undefined) { prefix = '-' + vendor.toLowerCase() + '-'; endEvent = transitions[vendor]; break; } } if (!endEvent && element.style.transitionProperty !== undefined) endEvent = 'transitionend'; return { end: endEvent, prefix: prefix }; } /***/ }, /* 81 */ /***/ function(module, exports) { 'use strict'; module.exports = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(81); var on = function on() {}; if (canUseDOM) { on = (function () { if (document.addEventListener) return function (node, eventName, handler, capture) { return node.addEventListener(eventName, handler, capture || false); };else if (document.attachEvent) return function (node, eventName, handler) { return node.attachEvent('on' + eventName, handler); }; })(); } module.exports = on; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _domHelpersActiveElement = __webpack_require__(84); var _domHelpersActiveElement2 = _interopRequireDefault(_domHelpersActiveElement); var _domHelpersQueryContains = __webpack_require__(86); var _domHelpersQueryContains2 = _interopRequireDefault(_domHelpersQueryContains); var _keycode = __webpack_require__(87); var _keycode2 = _interopRequireDefault(_keycode); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactPropTypesLibAll = __webpack_require__(56); var _reactPropTypesLibAll2 = _interopRequireDefault(_reactPropTypesLibAll); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _reactPropTypesLibIsRequiredForA11y = __webpack_require__(88); var _reactPropTypesLibIsRequiredForA11y2 = _interopRequireDefault(_reactPropTypesLibIsRequiredForA11y); var _uncontrollable = __webpack_require__(89); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _ButtonGroup = __webpack_require__(55); var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup); var _DropdownMenu = __webpack_require__(92); var _DropdownMenu2 = _interopRequireDefault(_DropdownMenu); var _DropdownToggle = __webpack_require__(123); var _DropdownToggle2 = _interopRequireDefault(_DropdownToggle); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsPropTypes = __webpack_require__(124); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var TOGGLE_ROLE = _DropdownToggle2['default'].defaultProps.bsRole; var MENU_ROLE = _DropdownMenu2['default'].defaultProps.bsRole; var propTypes = { /** * The menu will open above the dropdown button, instead of below it. */ dropup: _react2['default'].PropTypes.bool, /** * An html id attribute, necessary for assistive technologies, such as screen readers. * @type {string|number} * @required */ id: _reactPropTypesLibIsRequiredForA11y2['default'](_react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number])), componentClass: _reactPropTypesLibElementType2['default'], /** * The children of a Dropdown may be a `<Dropdown.Toggle>` or a `<Dropdown.Menu>`. * @type {node} */ children: _reactPropTypesLibAll2['default'](_utilsPropTypes.requiredRoles(TOGGLE_ROLE, MENU_ROLE), _utilsPropTypes.exclusiveRoles(MENU_ROLE)), /** * Whether or not component is disabled. */ disabled: _react2['default'].PropTypes.bool, /** * Align the menu to the right side of the Dropdown toggle */ pullRight: _react2['default'].PropTypes.bool, /** * Whether or not the Dropdown is visible. * * @controllable onToggle */ open: _react2['default'].PropTypes.bool, /** * A callback fired when the Dropdown closes. */ onClose: _react2['default'].PropTypes.func, /** * A callback fired when the Dropdown wishes to change visibility. Called with the requested * `open` value. * * ```js * function(Boolean isOpen) {} * ``` * @controllable open */ onToggle: _react2['default'].PropTypes.func, /** * A callback fired when a menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: _react2['default'].PropTypes.func, /** * If `'menuitem'`, causes the dropdown to behave like a menu item rather than * a menu button. */ role: _react2['default'].PropTypes.string }; var defaultProps = { componentClass: _ButtonGroup2['default'] }; var Dropdown = (function (_React$Component) { _inherits(Dropdown, _React$Component); function Dropdown(props, context) { _classCallCheck(this, Dropdown); _React$Component.call(this, props, context); this.handleClick = this.handleClick.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.handleClose = this.handleClose.bind(this); this._focusInDropdown = false; this.lastOpenEventType = null; } Dropdown.prototype.componentDidMount = function componentDidMount() { this.focusNextOnOpen(); }; Dropdown.prototype.componentWillUpdate = function componentWillUpdate(nextProps) { if (!nextProps.open && this.props.open) { this._focusInDropdown = _domHelpersQueryContains2['default'](_reactDom2['default'].findDOMNode(this.menu), _domHelpersActiveElement2['default'](document)); } }; Dropdown.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { var open = this.props.open; var prevOpen = prevProps.open; if (open && !prevOpen) { this.focusNextOnOpen(); } if (!open && prevOpen) { // if focus hasn't already moved from the menu lets return it // to the toggle if (this._focusInDropdown) { this._focusInDropdown = false; this.focus(); } } }; Dropdown.prototype.handleClick = function handleClick() { if (this.props.disabled) { return; } this.toggleOpen('click'); }; Dropdown.prototype.handleKeyDown = function handleKeyDown(event) { if (this.props.disabled) { return; } switch (event.keyCode) { case _keycode2['default'].codes.down: if (!this.props.open) { this.toggleOpen('keydown'); } else if (this.menu.focusNext) { this.menu.focusNext(); } event.preventDefault(); break; case _keycode2['default'].codes.esc: case _keycode2['default'].codes.tab: this.handleClose(event); break; default: } }; Dropdown.prototype.toggleOpen = function toggleOpen(eventType) { var open = !this.props.open; if (open) { this.lastOpenEventType = eventType; } if (this.props.onToggle) { this.props.onToggle(open); } }; Dropdown.prototype.handleClose = function handleClose() { if (!this.props.open) { return; } this.toggleOpen(null); }; Dropdown.prototype.focusNextOnOpen = function focusNextOnOpen() { var menu = this.menu; if (!menu.focusNext) { return; } if (this.lastOpenEventType === 'keydown' || this.props.role === 'menuitem') { menu.focusNext(); } }; Dropdown.prototype.focus = function focus() { var toggle = _reactDom2['default'].findDOMNode(this.toggle); if (toggle && toggle.focus) { toggle.focus(); } }; Dropdown.prototype.renderToggle = function renderToggle(child, props) { var _this = this; var ref = function ref(c) { _this.toggle = c; }; if (typeof child.ref === 'string') { true ? _warning2['default'](false, 'String refs are not supported on `<Dropdown.Toggle>` components. ' + 'To apply a ref to the component use the callback signature:\n\n ' + 'https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute') : undefined; } else { ref = _utilsCreateChainedFunction2['default'](child.ref, ref); } return _react.cloneElement(child, _extends({}, props, { ref: ref, bsClass: _utilsBootstrapUtils.prefix(props, 'toggle'), onClick: _utilsCreateChainedFunction2['default'](child.props.onClick, this.handleClick), onKeyDown: _utilsCreateChainedFunction2['default'](child.props.onKeyDown, this.handleKeyDown) })); }; Dropdown.prototype.renderMenu = function renderMenu(child, _ref) { var _this2 = this; var id = _ref.id; var onClose = _ref.onClose; var onSelect = _ref.onSelect; var props = _objectWithoutProperties(_ref, ['id', 'onClose', 'onSelect']); var ref = function ref(c) { _this2.menu = c; }; if (typeof child.ref === 'string') { true ? _warning2['default'](false, 'String refs are not supported on `<Dropdown.Menu>` components. ' + 'To apply a ref to the component use the callback signature:\n\n ' + 'https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute') : undefined; } else { ref = _utilsCreateChainedFunction2['default'](child.ref, ref); } return _react.cloneElement(child, _extends({}, props, { ref: ref, labelledBy: id, bsClass: _utilsBootstrapUtils.prefix(props, 'menu'), onClose: _utilsCreateChainedFunction2['default'](child.props.onClose, onClose, this.handleClose), onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, onSelect, this.handleClose) })); }; Dropdown.prototype.render = function render() { var _classes, _this3 = this; var _props = this.props; var Component = _props.componentClass; var id = _props.id; var dropup = _props.dropup; var disabled = _props.disabled; var pullRight = _props.pullRight; var open = _props.open; var onClose = _props.onClose; var onSelect = _props.onSelect; var role = _props.role; var bsClass = _props.bsClass; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['componentClass', 'id', 'dropup', 'disabled', 'pullRight', 'open', 'onClose', 'onSelect', 'role', 'bsClass', 'className', 'children']); delete props.onToggle; var classes = (_classes = {}, _classes[bsClass] = true, _classes.open = open, _classes.disabled = disabled, _classes); if (dropup) { classes[bsClass] = false; classes.dropup = true; } // This intentionally forwards bsSize and bsStyle (if set) to the // underlying component, to allow it to render size and style variants. return _react2['default'].createElement( Component, _extends({}, props, { className: _classnames2['default'](className, classes) }), _utilsValidComponentChildren2['default'].map(children, function (child) { switch (child.props.bsRole) { case TOGGLE_ROLE: return _this3.renderToggle(child, { id: id, disabled: disabled, open: open, role: role, bsClass: bsClass }); case MENU_ROLE: return _this3.renderMenu(child, { id: id, open: open, pullRight: pullRight, bsClass: bsClass, onClose: onClose, onSelect: onSelect }); default: return child; } }) ); }; return Dropdown; })(_react2['default'].Component); Dropdown.propTypes = propTypes; Dropdown.defaultProps = defaultProps; _utilsBootstrapUtils.bsClass('dropdown', Dropdown); var UncontrolledDropdown = _uncontrollable2['default'](Dropdown, { open: 'onToggle' }); UncontrolledDropdown.Toggle = _DropdownToggle2['default']; UncontrolledDropdown.Menu = _DropdownMenu2['default']; exports['default'] = UncontrolledDropdown; module.exports = exports['default']; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(77); exports.__esModule = true; /** * document.activeElement */ exports['default'] = activeElement; var _ownerDocument = __webpack_require__(85); var _ownerDocument2 = babelHelpers.interopRequireDefault(_ownerDocument); function activeElement() { var doc = arguments[0] === undefined ? document : arguments[0]; try { return doc.activeElement; } catch (e) {} } module.exports = exports['default']; /***/ }, /* 85 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = ownerDocument; function ownerDocument(node) { return node && node.ownerDocument || document; } module.exports = exports["default"]; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(81); var contains = (function () { var root = canUseDOM && document.documentElement; return root && root.contains ? function (context, node) { return context.contains(node); } : root && root.compareDocumentPosition ? function (context, node) { return context === node || !!(context.compareDocumentPosition(node) & 16); } : function (context, node) { if (node) do { if (node === context) return true; } while (node = node.parentNode); return false; }; })(); module.exports = contains; /***/ }, /* 87 */ /***/ function(module, exports) { // Source: http://jsfiddle.net/vWx8V/ // http://stackoverflow.com/questions/5603195/full-list-of-javascript-keycodes /** * Conenience method returns corresponding value for given keyName or keyCode. * * @param {Mixed} keyCode {Number} or keyName {String} * @return {Mixed} * @api public */ exports = module.exports = function(searchInput) { // Keyboard Events if (searchInput && 'object' === typeof searchInput) { var hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode if (hasKeyCode) searchInput = hasKeyCode } // Numbers if ('number' === typeof searchInput) return names[searchInput] // Everything else (cast to string) var search = String(searchInput) // check codes var foundNamedKey = codes[search.toLowerCase()] if (foundNamedKey) return foundNamedKey // check aliases var foundNamedKey = aliases[search.toLowerCase()] if (foundNamedKey) return foundNamedKey // weird character? if (search.length === 1) return search.charCodeAt(0) return undefined } /** * Get by name * * exports.code['enter'] // => 13 */ var codes = exports.code = exports.codes = { 'backspace': 8, 'tab': 9, 'enter': 13, 'shift': 16, 'ctrl': 17, 'alt': 18, 'pause/break': 19, 'caps lock': 20, 'esc': 27, 'space': 32, 'page up': 33, 'page down': 34, 'end': 35, 'home': 36, 'left': 37, 'up': 38, 'right': 39, 'down': 40, 'insert': 45, 'delete': 46, 'command': 91, 'left command': 91, 'right command': 93, 'numpad *': 106, 'numpad +': 107, 'numpad -': 109, 'numpad .': 110, 'numpad /': 111, 'num lock': 144, 'scroll lock': 145, 'my computer': 182, 'my calculator': 183, ';': 186, '=': 187, ',': 188, '-': 189, '.': 190, '/': 191, '`': 192, '[': 219, '\\': 220, ']': 221, "'": 222 } // Helper aliases var aliases = exports.aliases = { 'windows': 91, '⇧': 16, '⌥': 18, '⌃': 17, '⌘': 91, 'ctl': 17, 'control': 17, 'option': 18, 'pause': 19, 'break': 19, 'caps': 20, 'return': 13, 'escape': 27, 'spc': 32, 'pgup': 33, 'pgdn': 34, 'ins': 45, 'del': 46, 'cmd': 91 } /*! * Programatically add the following */ // lower case chars for (i = 97; i < 123; i++) codes[String.fromCharCode(i)] = i - 32 // numbers for (var i = 48; i < 58; i++) codes[i - 48] = i // function keys for (i = 1; i < 13; i++) codes['f'+i] = i + 111 // numpad keys for (i = 0; i < 10; i++) codes['numpad '+i] = i + 96 /** * Get by code * * exports.name[13] // => 'Enter' */ var names = exports.names = exports.title = {} // title for backward compat // Create reverse mapping for (i in codes) names[codes[i]] = i // Add aliases for (var alias in aliases) { codes[alias] = aliases[alias] } /***/ }, /* 88 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = isRequiredForA11y; function isRequiredForA11y(propType) { return function validate(props, propName, componentName) { if (props[propName] == null) { return new Error("The prop '" + propName + "' is required to make '" + componentName + "' accessible" + " for users using assistive technologies such as screen readers"); } return propType(props, propName, componentName); }; } module.exports = exports["default"]; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createUncontrollable = __webpack_require__(90); var _createUncontrollable2 = _interopRequireDefault(_createUncontrollable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var mixin = { shouldComponentUpdate: function shouldComponentUpdate() { //let the forceUpdate trigger the update return !this._notifying; } }; function set(component, propName, handler, value, args) { if (handler) { component._notifying = true; handler.call.apply(handler, [component, value].concat(args)); component._notifying = false; } component._values[propName] = value; if (component.isMounted()) component.forceUpdate(); } exports.default = (0, _createUncontrollable2.default)([mixin], set); module.exports = exports['default']; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = createUncontrollable; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(40); var _invariant2 = _interopRequireDefault(_invariant); var _utils = __webpack_require__(91); var utils = _interopRequireWildcard(_utils); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createUncontrollable(mixins, set) { return uncontrollable; function uncontrollable(Component, controlledValues) { var methods = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2]; var displayName = Component.displayName || Component.name || 'Component', basePropTypes = utils.getType(Component).propTypes, isCompositeComponent = utils.isReactComponent(Component), controlledProps = Object.keys(controlledValues), propTypes; var OMIT_PROPS = ['valueLink', 'checkedLink'].concat(controlledProps.map(utils.defaultKey)); propTypes = utils.uncontrolledPropTypes(controlledValues, basePropTypes, displayName); (0, _invariant2.default)(isCompositeComponent || !methods.length, '[uncontrollable] stateless function components cannot pass through methods ' + 'because they have no associated instances. Check component: ' + displayName + ', ' + 'attempting to pass through methods: ' + methods.join(', ')); methods = utils.transform(methods, function (obj, method) { obj[method] = function () { var _refs$inner; return (_refs$inner = this.refs.inner)[method].apply(_refs$inner, arguments); }; }, {}); var component = _react2.default.createClass(_extends({ displayName: 'Uncontrolled(' + displayName + ')', mixins: mixins, propTypes: propTypes }, methods, { componentWillMount: function componentWillMount() { var _this = this; var props = this.props; this._values = {}; controlledProps.forEach(function (key) { _this._values[key] = props[utils.defaultKey(key)]; }); }, /** * If a prop switches from controlled to Uncontrolled * reset its value to the defaultValue */ componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var _this2 = this; var props = this.props; controlledProps.forEach(function (key) { if (utils.getValue(nextProps, key) === undefined && utils.getValue(props, key) !== undefined) { _this2._values[key] = nextProps[utils.defaultKey(key)]; } }); }, render: function render() { var _this3 = this; var newProps = {}, props = omitProps(this.props); utils.each(controlledValues, function (handle, propName) { var linkPropName = utils.getLinkName(propName), prop = _this3.props[propName]; if (linkPropName && !isProp(_this3.props, propName) && isProp(_this3.props, linkPropName)) { prop = _this3.props[linkPropName].value; } newProps[propName] = prop !== undefined ? prop : _this3._values[propName]; newProps[handle] = setAndNotify.bind(_this3, propName); }); newProps = _extends({}, props, newProps, { ref: isCompositeComponent ? 'inner' : null }); return _react2.default.createElement(Component, newProps); } })); component.ControlledComponent = Component; /** * useful when wrapping a Component and you want to control * everything */ component.deferControlTo = function (newComponent) { var additions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var nextMethods = arguments[2]; return uncontrollable(newComponent, _extends({}, controlledValues, additions), nextMethods); }; return component; function setAndNotify(propName, value) { var linkName = utils.getLinkName(propName), handler = this.props[controlledValues[propName]]; if (linkName && isProp(this.props, linkName) && !handler) { handler = this.props[linkName].requestChange; } for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } set(this, propName, handler, value, args); } function isProp(props, prop) { return props[prop] !== undefined; } function omitProps(props) { var result = {}; utils.each(props, function (value, key) { if (OMIT_PROPS.indexOf(key) === -1) result[key] = value; }); return result; } } } module.exports = exports['default']; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.version = undefined; exports.customPropType = customPropType; exports.uncontrolledPropTypes = uncontrolledPropTypes; exports.getType = getType; exports.getValue = getValue; exports.getLinkName = getLinkName; exports.defaultKey = defaultKey; exports.chain = chain; exports.transform = transform; exports.each = each; exports.isReactComponent = isReactComponent; exports.has = has; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(40); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function customPropType(handler, propType, name) { return function (props, propName) { if (props[propName] !== undefined) { if (!props[handler]) { return new Error('You have provided a `' + propName + '` prop to ' + '`' + name + '` without an `' + handler + '` handler. This will render a read-only field. ' + 'If the field should be mutable use `' + defaultKey(propName) + '`. Otherwise, set `' + handler + '`'); } return propType && propType(props, propName, name); } }; } function uncontrolledPropTypes(controlledValues, basePropTypes, displayName) { var propTypes = {}; if (("development") !== 'production' && basePropTypes) { transform(controlledValues, function (obj, handler, prop) { var type = basePropTypes[prop]; (0, _invariant2.default)(typeof handler === 'string' && handler.trim().length, 'Uncontrollable - [%s]: the prop `%s` needs a valid handler key name in order to make it uncontrollable', displayName, prop); obj[prop] = customPropType(handler, type, displayName); if (type !== undefined) obj[defaultKey(prop)] = type; }, propTypes); } return propTypes; } var version = exports.version = _react2.default.version.split('.').map(parseFloat); function getType(component) { if (version[0] >= 15 || version[0] === 0 && version[1] >= 13) return component; return component.type; } function getValue(props, name) { var linkPropName = getLinkName(name); if (linkPropName && !isProp(props, name) && isProp(props, linkPropName)) return props[linkPropName].value; return props[name]; } function isProp(props, prop) { return props[prop] !== undefined; } function getLinkName(name) { return name === 'value' ? 'valueLink' : name === 'checked' ? 'checkedLink' : null; } function defaultKey(key) { return 'default' + key.charAt(0).toUpperCase() + key.substr(1); } function chain(thisArg, a, b) { return function chainedFunction() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } a && a.call.apply(a, [thisArg].concat(args)); b && b.call.apply(b, [thisArg].concat(args)); }; } function transform(obj, cb, seed) { each(obj, cb.bind(null, seed = seed || (Array.isArray(obj) ? [] : {}))); return seed; } function each(obj, cb, thisArg) { if (Array.isArray(obj)) return obj.forEach(cb, thisArg); for (var key in obj) { if (has(obj, key)) cb.call(thisArg, obj[key], key, obj); } } /** * 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 isReactComponent(component) { return !!(component && component.prototype && component.prototype.isReactComponent); } function has(o, k) { return o ? Object.prototype.hasOwnProperty.call(o, k) : false; } /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _Array$from = __webpack_require__(93)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _keycode = __webpack_require__(87); var _keycode2 = _interopRequireDefault(_keycode); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactOverlaysLibRootCloseWrapper = __webpack_require__(118); var _reactOverlaysLibRootCloseWrapper2 = _interopRequireDefault(_reactOverlaysLibRootCloseWrapper); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var propTypes = { open: _react2['default'].PropTypes.bool, pullRight: _react2['default'].PropTypes.bool, onClose: _react2['default'].PropTypes.func, labelledBy: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]), onSelect: _react2['default'].PropTypes.func }; var defaultProps = { bsRole: 'menu', pullRight: false }; var DropdownMenu = (function (_React$Component) { _inherits(DropdownMenu, _React$Component); function DropdownMenu(props) { _classCallCheck(this, DropdownMenu); _React$Component.call(this, props); this.handleKeyDown = this.handleKeyDown.bind(this); } DropdownMenu.prototype.handleKeyDown = function handleKeyDown(event) { switch (event.keyCode) { case _keycode2['default'].codes.down: this.focusNext(); event.preventDefault(); break; case _keycode2['default'].codes.up: this.focusPrevious(); event.preventDefault(); break; case _keycode2['default'].codes.esc: case _keycode2['default'].codes.tab: this.props.onClose(event); break; default: } }; DropdownMenu.prototype.getItemsAndActiveIndex = function getItemsAndActiveIndex() { var items = this.getFocusableMenuItems(); var activeIndex = items.indexOf(document.activeElement); return { items: items, activeIndex: activeIndex }; }; DropdownMenu.prototype.getFocusableMenuItems = function getFocusableMenuItems() { var node = _reactDom2['default'].findDOMNode(this); if (!node) { return []; } return _Array$from(node.querySelectorAll('[tabIndex="-1"]')); }; DropdownMenu.prototype.focusNext = function focusNext() { var _getItemsAndActiveIndex = this.getItemsAndActiveIndex(); var items = _getItemsAndActiveIndex.items; var activeIndex = _getItemsAndActiveIndex.activeIndex; if (items.length === 0) { return; } var nextIndex = activeIndex === items.length - 1 ? 0 : activeIndex + 1; items[nextIndex].focus(); }; DropdownMenu.prototype.focusPrevious = function focusPrevious() { var _getItemsAndActiveIndex2 = this.getItemsAndActiveIndex(); var items = _getItemsAndActiveIndex2.items; var activeIndex = _getItemsAndActiveIndex2.activeIndex; if (items.length === 0) { return; } var prevIndex = activeIndex === 0 ? items.length - 1 : activeIndex - 1; items[prevIndex].focus(); }; DropdownMenu.prototype.render = function render() { var _extends2, _this = this; var _props = this.props; var open = _props.open; var pullRight = _props.pullRight; var onClose = _props.onClose; var labelledBy = _props.labelledBy; var onSelect = _props.onSelect; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['open', 'pullRight', 'onClose', 'labelledBy', 'onSelect', 'className', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'right')] = pullRight, _extends2)); var list = _react2['default'].createElement( 'ul', _extends({}, elementProps, { role: 'menu', className: _classnames2['default'](className, classes), 'aria-labelledby': labelledBy }), _utilsValidComponentChildren2['default'].map(children, function (child) { return _react2['default'].cloneElement(child, { onKeyDown: _utilsCreateChainedFunction2['default'](child.props.onKeyDown, _this.handleKeyDown), onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, onSelect) }); }) ); if (open) { return _react2['default'].createElement( _reactOverlaysLibRootCloseWrapper2['default'], { noWrap: true, onRootClose: onClose }, list ); } return list; }; return DropdownMenu; })(_react2['default'].Component); DropdownMenu.propTypes = propTypes; DropdownMenu.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('dropdown-menu', DropdownMenu); module.exports = exports['default']; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(94), __esModule: true }; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(95); __webpack_require__(111); module.exports = __webpack_require__(13).Array.from; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $at = __webpack_require__(96)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(98)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(97) , defined = __webpack_require__(26); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }, /* 97 */ /***/ function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(99) , $export = __webpack_require__(11) , redefine = __webpack_require__(100) , hide = __webpack_require__(101) , has = __webpack_require__(104) , Iterators = __webpack_require__(105) , $iterCreate = __webpack_require__(106) , setToStringTag = __webpack_require__(107) , getProto = __webpack_require__(7).getProto , ITERATOR = __webpack_require__(108)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , methods, key; // Fix native if($native){ var IteratorPrototype = getProto($default.call(new Base)); // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // FF fix if(!LIBRARY && has(proto, FF_ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: !DEF_VALUES ? $default : getMethod('entries') }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }, /* 99 */ /***/ function(module, exports) { module.exports = true; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(101); /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(7) , createDesc = __webpack_require__(102); module.exports = __webpack_require__(103) ? function(object, key, value){ return $.setDesc(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }, /* 102 */ /***/ function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(29)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 104 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 105 */ /***/ function(module, exports) { module.exports = {}; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(7) , descriptor = __webpack_require__(102) , setToStringTag = __webpack_require__(107) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(101)(IteratorPrototype, __webpack_require__(108)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = $.create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { var def = __webpack_require__(7).setDesc , has = __webpack_require__(104) , TAG = __webpack_require__(108)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { var store = __webpack_require__(109)('wks') , uid = __webpack_require__(110) , Symbol = __webpack_require__(12).Symbol; module.exports = function(name){ return store[name] || (store[name] = Symbol && Symbol[name] || (Symbol || uid)('Symbol.' + name)); }; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(12) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }, /* 110 */ /***/ function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ctx = __webpack_require__(14) , $export = __webpack_require__(11) , toObject = __webpack_require__(25) , call = __webpack_require__(112) , isArrayIter = __webpack_require__(113) , toLength = __webpack_require__(114) , getIterFn = __webpack_require__(115); $export($export.S + $export.F * !__webpack_require__(117)(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = toObject(arrayLike) , C = typeof this == 'function' ? this : Array , $$ = arguments , $$len = $$.length , mapfn = $$len > 1 ? $$[1] : undefined , mapping = mapfn !== undefined , index = 0 , iterFn = getIterFn(O) , length, result, step, iterator; if(mapping)mapfn = ctx(mapfn, $$len > 2 ? $$[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ result[index] = mapping ? call(iterator, mapfn, [step.value, index], true) : step.value; } } else { length = toLength(O.length); for(result = new C(length); length > index; index++){ result[index] = mapping ? mapfn(O[index], index) : O[index]; } } result.length = index; return result; } }); /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(18); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(105) , ITERATOR = __webpack_require__(108)('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(97) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(116) , ITERATOR = __webpack_require__(108)('iterator') , Iterators = __webpack_require__(105); module.exports = __webpack_require__(13).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(28) , TAG = __webpack_require__(108)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = (O = Object(it))[TAG]) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(108)('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ return {done: safe = true}; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _addEventListener = __webpack_require__(119); var _addEventListener2 = _interopRequireDefault(_addEventListener); var _createChainedFunction = __webpack_require__(121); var _createChainedFunction2 = _interopRequireDefault(_createChainedFunction); var _ownerDocument = __webpack_require__(122); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // TODO: Consider using an ES6 symbol here, once we use babel-runtime. var CLICK_WAS_INSIDE = '__click_was_inside'; var counter = 0; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } function getSuppressRootClose() { var id = CLICK_WAS_INSIDE + '_' + counter++; return { id: id, suppressRootClose: function suppressRootClose(event) { // Tag the native event to prevent the root close logic on document click. // This seems safer than using event.nativeEvent.stopImmediatePropagation(), // which is only supported in IE >= 9. event.nativeEvent[id] = true; } }; } var RootCloseWrapper = function (_React$Component) { _inherits(RootCloseWrapper, _React$Component); function RootCloseWrapper(props) { _classCallCheck(this, RootCloseWrapper); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(RootCloseWrapper).call(this, props)); _this.handleDocumentMouse = _this.handleDocumentMouse.bind(_this); _this.handleDocumentKeyUp = _this.handleDocumentKeyUp.bind(_this); var _getSuppressRootClose = getSuppressRootClose(); var id = _getSuppressRootClose.id; var suppressRootClose = _getSuppressRootClose.suppressRootClose; _this._suppressRootId = id; _this._suppressRootCloseHandler = suppressRootClose; return _this; } _createClass(RootCloseWrapper, [{ key: 'bindRootCloseHandlers', value: function bindRootCloseHandlers() { var doc = (0, _ownerDocument2.default)(this); this._onDocumentMouseListener = (0, _addEventListener2.default)(doc, this.props.event, this.handleDocumentMouse); this._onDocumentKeyupListener = (0, _addEventListener2.default)(doc, 'keyup', this.handleDocumentKeyUp); } }, { key: 'handleDocumentMouse', value: function handleDocumentMouse(e) { // This is now the native event. if (e[this._suppressRootId]) { return; } if (this.props.disabled || isModifiedEvent(e) || !isLeftClickEvent(e)) { return; } this.props.onRootClose && this.props.onRootClose(); } }, { key: 'handleDocumentKeyUp', value: function handleDocumentKeyUp(e) { if (e.keyCode === 27 && this.props.onRootClose) { this.props.onRootClose(); } } }, { key: 'unbindRootCloseHandlers', value: function unbindRootCloseHandlers() { if (this._onDocumentMouseListener) { this._onDocumentMouseListener.remove(); } if (this._onDocumentKeyupListener) { this._onDocumentKeyupListener.remove(); } } }, { key: 'componentDidMount', value: function componentDidMount() { this.bindRootCloseHandlers(); } }, { key: 'render', value: function render() { var _props = this.props; var event = _props.event; var noWrap = _props.noWrap; var children = _props.children; var child = _react2.default.Children.only(children); var handlerName = event == 'click' ? 'onClick' : 'onMouseDown'; if (noWrap) { return _react2.default.cloneElement(child, _defineProperty({}, handlerName, (0, _createChainedFunction2.default)(this._suppressRootCloseHandler, child.props[handlerName]))); } // Wrap the child in a new element, so the child won't have to handle // potentially combining multiple onClick listeners. return _react2.default.createElement( 'div', _defineProperty({}, handlerName, this._suppressRootCloseHandler), child ); } }, { key: 'getWrappedDOMNode', value: function getWrappedDOMNode() { // We can't use a ref to identify the wrapped child, since we might be // stealing the ref from the owner, but we know exactly the DOM structure // that will be rendered, so we can just do this to get the child's DOM // node for doing size calculations in OverlayMixin. var node = _reactDom2.default.findDOMNode(this); return this.props.noWrap ? node : node.firstChild; } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unbindRootCloseHandlers(); } }]); return RootCloseWrapper; }(_react2.default.Component); exports.default = RootCloseWrapper; RootCloseWrapper.displayName = 'RootCloseWrapper'; RootCloseWrapper.propTypes = { onRootClose: _react2.default.PropTypes.func, /** * Disable the the RootCloseWrapper, preventing it from triggering * `onRootClose`. */ disabled: _react2.default.PropTypes.bool, /** * Passes the suppress click handler directly to the child component instead * of placing it on a wrapping div. Only use when you can be sure the child * properly handle the click event. */ noWrap: _react2.default.PropTypes.bool, /** * Choose which document mouse event to bind to */ event: _react2.default.PropTypes.oneOf(['click', 'mousedown']) }; RootCloseWrapper.defaultProps = { event: 'click' }; module.exports = exports['default']; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (node, event, handler) { (0, _on2.default)(node, event, handler); return { remove: function remove() { (0, _off2.default)(node, event, handler); } }; }; var _on = __webpack_require__(82); var _on2 = _interopRequireDefault(_on); var _off = __webpack_require__(120); var _off2 = _interopRequireDefault(_off); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports['default']; /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(81); var off = function off() {}; if (canUseDOM) { off = (function () { if (document.addEventListener) return function (node, eventName, handler, capture) { return node.removeEventListener(eventName, handler, capture || false); };else if (document.attachEvent) return function (node, eventName, handler) { return node.detachEvent('on' + eventName, handler); }; })(); } module.exports = off; /***/ }, /* 121 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * Safe chained function * * Will only create a new function if needed, * otherwise will pass back existing functions or null. * * @param {function} functions to chain * @returns {function|null} */ function createChainedFunction() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } return funcs.filter(function (f) { return f != null; }).reduce(function (acc, f) { if (typeof f !== 'function') { throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.'); } if (acc === null) { return f; } return function chainedFunction() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } acc.apply(this, args); f.apply(this, args); }; }, null); } exports.default = createChainedFunction; module.exports = exports['default']; /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (componentOrElement) { return (0, _ownerDocument2.default)(_reactDom2.default.findDOMNode(componentOrElement)); }; var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _ownerDocument = __webpack_require__(85); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports['default']; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _Button = __webpack_require__(54); var _Button2 = _interopRequireDefault(_Button); var _SafeAnchor = __webpack_require__(51); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { noCaret: _react2['default'].PropTypes.bool, open: _react2['default'].PropTypes.bool, title: _react2['default'].PropTypes.string, useAnchor: _react2['default'].PropTypes.bool }; var defaultProps = { open: false, useAnchor: false, bsRole: 'toggle' }; var DropdownToggle = (function (_React$Component) { _inherits(DropdownToggle, _React$Component); function DropdownToggle() { _classCallCheck(this, DropdownToggle); _React$Component.apply(this, arguments); } DropdownToggle.prototype.render = function render() { var _props = this.props; var noCaret = _props.noCaret; var open = _props.open; var useAnchor = _props.useAnchor; var bsClass = _props.bsClass; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['noCaret', 'open', 'useAnchor', 'bsClass', 'className', 'children']); delete props.bsRole; var Component = useAnchor ? _SafeAnchor2['default'] : _Button2['default']; var useCaret = !noCaret; // This intentionally forwards bsSize and bsStyle (if set) to the // underlying component, to allow it to render size and style variants. // FIXME: Should this really fall back to `title` as children? return _react2['default'].createElement( Component, _extends({}, props, { role: 'button', className: _classnames2['default'](className, bsClass), 'aria-haspopup': true, 'aria-expanded': open }), children || props.title, useCaret && ' ', useCaret && _react2['default'].createElement('span', { className: 'caret' }) ); }; return DropdownToggle; })(_react2['default'].Component); DropdownToggle.propTypes = propTypes; DropdownToggle.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('dropdown-toggle', DropdownToggle); module.exports = exports['default']; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports.requiredRoles = requiredRoles; exports.exclusiveRoles = exclusiveRoles; var _reactPropTypesLibCommon = __webpack_require__(53); var _ValidComponentChildren = __webpack_require__(43); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function requiredRoles() { for (var _len = arguments.length, roles = Array(_len), _key = 0; _key < _len; _key++) { roles[_key] = arguments[_key]; } return _reactPropTypesLibCommon.createChainableTypeChecker(function (props, propName, component) { var missing = undefined; roles.every(function (role) { if (!_ValidComponentChildren2['default'].some(props.children, function (child) { return child.props.bsRole === role; })) { missing = role; return false; } return true; }); if (missing) { return new Error('(children) ' + component + ' - Missing a required child with bsRole: ' + (missing + '. ' + component + ' must have at least one child of each of ') + ('the following bsRoles: ' + roles.join(', '))); } return null; }); } function exclusiveRoles() { for (var _len2 = arguments.length, roles = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { roles[_key2] = arguments[_key2]; } return _reactPropTypesLibCommon.createChainableTypeChecker(function (props, propName, component) { var duplicate = undefined; roles.every(function (role) { var childrenWithRole = _ValidComponentChildren2['default'].filter(props.children, function (child) { return child.props.bsRole === role; }); if (childrenWithRole.length > 1) { duplicate = role; return false; } return true; }); if (duplicate) { return new Error('(children) ' + component + ' - Duplicate children detected of bsRole: ' + (duplicate + '. Only one child each allowed with the following ') + ('bsRoles: ' + roles.join(', '))); } return null; }); } /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(20)['default']; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Dropdown = __webpack_require__(83); var _Dropdown2 = _interopRequireDefault(_Dropdown); var _utilsSplitComponentProps = __webpack_require__(126); var _utilsSplitComponentProps2 = _interopRequireDefault(_utilsSplitComponentProps); var propTypes = _extends({}, _Dropdown2['default'].propTypes, { // Toggle props. bsStyle: _react2['default'].PropTypes.string, bsSize: _react2['default'].PropTypes.string, title: _react2['default'].PropTypes.node.isRequired, noCaret: _react2['default'].PropTypes.bool, // Override generated docs from <Dropdown>. /** * @private */ children: _react2['default'].PropTypes.node }); var DropdownButton = (function (_React$Component) { _inherits(DropdownButton, _React$Component); function DropdownButton() { _classCallCheck(this, DropdownButton); _React$Component.apply(this, arguments); } DropdownButton.prototype.render = function render() { var _props = this.props; var bsSize = _props.bsSize; var bsStyle = _props.bsStyle; var title = _props.title; var children = _props.children; var props = _objectWithoutProperties(_props, ['bsSize', 'bsStyle', 'title', 'children']); var _splitComponentProps = _utilsSplitComponentProps2['default'](props, _Dropdown2['default'].ControlledComponent); var dropdownProps = _splitComponentProps[0]; var toggleProps = _splitComponentProps[1]; return _react2['default'].createElement( _Dropdown2['default'], _extends({}, dropdownProps, { bsSize: bsSize, bsStyle: bsStyle }), _react2['default'].createElement( _Dropdown2['default'].Toggle, _extends({}, toggleProps, { bsSize: bsSize, bsStyle: bsStyle }), title ), _react2['default'].createElement( _Dropdown2['default'].Menu, null, children ) ); }; return DropdownButton; })(_react2['default'].Component); DropdownButton.propTypes = propTypes; exports['default'] = DropdownButton; module.exports = exports['default']; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$entries = __webpack_require__(35)["default"]; exports.__esModule = true; exports["default"] = splitComponentProps; function splitComponentProps(props, Component) { var componentPropTypes = Component.propTypes; var parentProps = {}; var childProps = {}; _Object$entries(props).forEach(function (_ref) { var propName = _ref[0]; var propValue = _ref[1]; if (componentPropTypes[propName]) { parentProps[propName] = propValue; } else { childProps[propName] = propValue; } }); return [parentProps, childProps]; } module.exports = exports["default"]; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactOverlaysLibTransition = __webpack_require__(79); var _reactOverlaysLibTransition2 = _interopRequireDefault(_reactOverlaysLibTransition); var propTypes = { /** * Show the component; triggers the fade in or fade out animation */ 'in': _react2['default'].PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: _react2['default'].PropTypes.bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ transitionAppear: _react2['default'].PropTypes.bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: _react2['default'].PropTypes.number, /** * Callback fired before the component fades in */ onEnter: _react2['default'].PropTypes.func, /** * Callback fired after the component starts to fade in */ onEntering: _react2['default'].PropTypes.func, /** * Callback fired after the has component faded in */ onEntered: _react2['default'].PropTypes.func, /** * Callback fired before the component fades out */ onExit: _react2['default'].PropTypes.func, /** * Callback fired after the component starts to fade out */ onExiting: _react2['default'].PropTypes.func, /** * Callback fired after the component has faded out */ onExited: _react2['default'].PropTypes.func }; var defaultProps = { 'in': false, timeout: 300, unmountOnExit: false, transitionAppear: false }; var Fade = (function (_React$Component) { _inherits(Fade, _React$Component); function Fade() { _classCallCheck(this, Fade); _React$Component.apply(this, arguments); } Fade.prototype.render = function render() { return _react2['default'].createElement(_reactOverlaysLibTransition2['default'], _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'fade'), enteredClassName: 'in', enteringClassName: 'in' })); }; return Fade; })(_react2['default'].Component); Fade.propTypes = propTypes; Fade.defaultProps = defaultProps; exports['default'] = Fade; module.exports = exports['default']; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { horizontal: _react2['default'].PropTypes.bool, inline: _react2['default'].PropTypes.bool, componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { horizontal: false, inline: false, componentClass: 'form' }; var Form = (function (_React$Component) { _inherits(Form, _React$Component); function Form() { _classCallCheck(this, Form); _React$Component.apply(this, arguments); } Form.prototype.render = function render() { var _props = this.props; var horizontal = _props.horizontal; var inline = _props.inline; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['horizontal', 'inline', 'componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = []; if (horizontal) { classes.push(_utilsBootstrapUtils.prefix(bsProps, 'horizontal')); } if (inline) { classes.push(_utilsBootstrapUtils.prefix(bsProps, 'inline')); } return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Form; })(_react2['default'].Component); Form.propTypes = propTypes; Form.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('form', Form); module.exports = exports['default']; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _FormControlFeedback = __webpack_require__(130); var _FormControlFeedback2 = _interopRequireDefault(_FormControlFeedback); var _FormControlStatic = __webpack_require__(131); var _FormControlStatic2 = _interopRequireDefault(_FormControlStatic); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'], /** * Only relevant if `componentClass` is `'input'`. */ type: _react2['default'].PropTypes.string, /** * Uses `controlId` from `<FormGroup>` if not explicitly specified. */ id: _react2['default'].PropTypes.string }; var defaultProps = { componentClass: 'input' }; var contextTypes = { $bs_formGroup: _react2['default'].PropTypes.object }; var FormControl = (function (_React$Component) { _inherits(FormControl, _React$Component); function FormControl() { _classCallCheck(this, FormControl); _React$Component.apply(this, arguments); } FormControl.prototype.render = function render() { var formGroup = this.context.$bs_formGroup; var controlId = formGroup && formGroup.controlId; var _props = this.props; var Component = _props.componentClass; var type = _props.type; var _props$id = _props.id; var id = _props$id === undefined ? controlId : _props$id; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'type', 'id', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; true ? _warning2['default'](controlId == null || id === controlId, '`controlId` is ignored on `<FormControl>` when `id` is specified.') : undefined; // input[type="file"] should not have .form-control. var classes = undefined; if (type !== 'file') { classes = _utilsBootstrapUtils.getClassSet(bsProps); } return _react2['default'].createElement(Component, _extends({}, elementProps, { type: type, id: id, className: _classnames2['default'](className, classes) })); }; return FormControl; })(_react2['default'].Component); FormControl.propTypes = propTypes; FormControl.defaultProps = defaultProps; FormControl.contextTypes = contextTypes; FormControl.Feedback = _FormControlFeedback2['default']; FormControl.Static = _FormControlStatic2['default']; exports['default'] = _utilsBootstrapUtils.bsClass('form-control', FormControl); module.exports = exports['default']; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Glyphicon = __webpack_require__(63); var _Glyphicon2 = _interopRequireDefault(_Glyphicon); var _utilsBootstrapUtils = __webpack_require__(34); var defaultProps = { bsRole: 'feedback' }; var contextTypes = { $bs_formGroup: _react2['default'].PropTypes.object }; var FormControlFeedback = (function (_React$Component) { _inherits(FormControlFeedback, _React$Component); function FormControlFeedback() { _classCallCheck(this, FormControlFeedback); _React$Component.apply(this, arguments); } FormControlFeedback.prototype.getGlyph = function getGlyph(validationState) { switch (validationState) { case 'success': return 'ok'; case 'warning': return 'warning-sign'; case 'error': return 'remove'; default: return null; } }; FormControlFeedback.prototype.renderDefaultFeedback = function renderDefaultFeedback(formGroup, className, classes, elementProps) { var glyph = this.getGlyph(formGroup && formGroup.validationState); if (!glyph) { return null; } return _react2['default'].createElement(_Glyphicon2['default'], _extends({}, elementProps, { glyph: glyph, className: _classnames2['default'](className, classes) })); }; FormControlFeedback.prototype.render = function render() { var _props = this.props; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['className', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); if (!children) { return this.renderDefaultFeedback(this.context.$bs_formGroup, className, classes, elementProps); } var child = _react2['default'].Children.only(children); return _react2['default'].cloneElement(child, _extends({}, elementProps, { className: _classnames2['default'](child.props.className, className, classes) })); }; return FormControlFeedback; })(_react2['default'].Component); FormControlFeedback.defaultProps = defaultProps; FormControlFeedback.contextTypes = contextTypes; exports['default'] = _utilsBootstrapUtils.bsClass('form-control-feedback', FormControlFeedback); module.exports = exports['default']; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { componentClass: 'p' }; var FormControlStatic = (function (_React$Component) { _inherits(FormControlStatic, _React$Component); function FormControlStatic() { _classCallCheck(this, FormControlStatic); _React$Component.apply(this, arguments); } FormControlStatic.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return FormControlStatic; })(_react2['default'].Component); FormControlStatic.propTypes = propTypes; FormControlStatic.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('form-control-static', FormControlStatic); module.exports = exports['default']; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var propTypes = { /** * Sets `id` on `<FormControl>` and `htmlFor` on `<FormGroup.Label>`. */ controlId: _react2['default'].PropTypes.string, validationState: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']) }; var childContextTypes = { $bs_formGroup: _react2['default'].PropTypes.object.isRequired }; var FormGroup = (function (_React$Component) { _inherits(FormGroup, _React$Component); function FormGroup() { _classCallCheck(this, FormGroup); _React$Component.apply(this, arguments); } FormGroup.prototype.getChildContext = function getChildContext() { var _props = this.props; var controlId = _props.controlId; var validationState = _props.validationState; return { $bs_formGroup: { controlId: controlId, validationState: validationState } }; }; FormGroup.prototype.hasFeedback = function hasFeedback(children) { var _this = this; return _utilsValidComponentChildren2['default'].some(children, function (child) { return child.props.bsRole === 'feedback' || child.props.children && _this.hasFeedback(child.props.children); }); }; FormGroup.prototype.render = function render() { var _props2 = this.props; var validationState = _props2.validationState; var className = _props2.className; var children = _props2.children; var props = _objectWithoutProperties(_props2, ['validationState', 'className', 'children']); var _splitBsPropsAndOmit = _utilsBootstrapUtils.splitBsPropsAndOmit(props, ['controlId']); var bsProps = _splitBsPropsAndOmit[0]; var elementProps = _splitBsPropsAndOmit[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), { 'has-feedback': this.hasFeedback(children) }); if (validationState) { classes['has-' + validationState] = true; } return _react2['default'].createElement( 'div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), children ); }; return FormGroup; })(_react2['default'].Component); FormGroup.propTypes = propTypes; FormGroup.childContextTypes = childContextTypes; exports['default'] = _utilsBootstrapUtils.bsClass('form-group', _utilsBootstrapUtils.bsSizes([_utilsStyleConfig.Size.LARGE, _utilsStyleConfig.Size.SMALL], FormGroup)); module.exports = exports['default']; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { /** * Turn any fixed-width grid layout into a full-width layout by this property. * * Adds `container-fluid` class. */ fluid: _react2['default'].PropTypes.bool, /** * You can use a custom element for this component */ componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { componentClass: 'div', fluid: false }; var Grid = (function (_React$Component) { _inherits(Grid, _React$Component); function Grid() { _classCallCheck(this, Grid); _React$Component.apply(this, arguments); } Grid.prototype.render = function render() { var _props = this.props; var fluid = _props.fluid; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['fluid', 'componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.prefix(bsProps, fluid && 'fluid'); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Grid; })(_react2['default'].Component); Grid.propTypes = propTypes; Grid.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('container', Grid); module.exports = exports['default']; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var HelpBlock = (function (_React$Component) { _inherits(HelpBlock, _React$Component); function HelpBlock() { _classCallCheck(this, HelpBlock); _React$Component.apply(this, arguments); } HelpBlock.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('span', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return HelpBlock; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('help-block', HelpBlock); module.exports = exports['default']; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { /** * Sets image as responsive image */ responsive: _react2['default'].PropTypes.bool, /** * Sets image shape as rounded */ rounded: _react2['default'].PropTypes.bool, /** * Sets image shape as circle */ circle: _react2['default'].PropTypes.bool, /** * Sets image shape as thumbnail */ thumbnail: _react2['default'].PropTypes.bool }; var defaultProps = { responsive: false, rounded: false, circle: false, thumbnail: false }; var Image = (function (_React$Component) { _inherits(Image, _React$Component); function Image() { _classCallCheck(this, Image); _React$Component.apply(this, arguments); } Image.prototype.render = function render() { var _classes; var _props = this.props; var responsive = _props.responsive; var rounded = _props.rounded; var circle = _props.circle; var thumbnail = _props.thumbnail; var className = _props.className; var props = _objectWithoutProperties(_props, ['responsive', 'rounded', 'circle', 'thumbnail', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = (_classes = {}, _classes[_utilsBootstrapUtils.prefix(bsProps, 'responsive')] = responsive, _classes[_utilsBootstrapUtils.prefix(bsProps, 'rounded')] = rounded, _classes[_utilsBootstrapUtils.prefix(bsProps, 'circle')] = circle, _classes[_utilsBootstrapUtils.prefix(bsProps, 'thumbnail')] = thumbnail, _classes); return _react2['default'].createElement('img', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Image; })(_react2['default'].Component); Image.propTypes = propTypes; Image.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('img', Image); module.exports = exports['default']; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _InputGroupAddon = __webpack_require__(137); var _InputGroupAddon2 = _interopRequireDefault(_InputGroupAddon); var _InputGroupButton = __webpack_require__(138); var _InputGroupButton2 = _interopRequireDefault(_InputGroupButton); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var InputGroup = (function (_React$Component) { _inherits(InputGroup, _React$Component); function InputGroup() { _classCallCheck(this, InputGroup); _React$Component.apply(this, arguments); } InputGroup.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('span', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return InputGroup; })(_react2['default'].Component); InputGroup.Addon = _InputGroupAddon2['default']; InputGroup.Button = _InputGroupButton2['default']; exports['default'] = _utilsBootstrapUtils.bsClass('input-group', _utilsBootstrapUtils.bsSizes([_utilsStyleConfig.Size.LARGE, _utilsStyleConfig.Size.SMALL], InputGroup)); module.exports = exports['default']; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var InputGroupAddon = (function (_React$Component) { _inherits(InputGroupAddon, _React$Component); function InputGroupAddon() { _classCallCheck(this, InputGroupAddon); _React$Component.apply(this, arguments); } InputGroupAddon.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('span', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return InputGroupAddon; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('input-group-addon', InputGroupAddon); module.exports = exports['default']; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var InputGroupButton = (function (_React$Component) { _inherits(InputGroupButton, _React$Component); function InputGroupButton() { _classCallCheck(this, InputGroupButton); _React$Component.apply(this, arguments); } InputGroupButton.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('span', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return InputGroupButton; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('input-group-btn', InputGroupButton); module.exports = exports['default']; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { componentClass: 'div' }; var Jumbotron = (function (_React$Component) { _inherits(Jumbotron, _React$Component); function Jumbotron() { _classCallCheck(this, Jumbotron); _React$Component.apply(this, arguments); } Jumbotron.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Jumbotron; })(_react2['default'].Component); Jumbotron.propTypes = propTypes; Jumbotron.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('jumbotron', Jumbotron); module.exports = exports['default']; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _Object$values = __webpack_require__(45)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var Label = (function (_React$Component) { _inherits(Label, _React$Component); function Label() { _classCallCheck(this, Label); _React$Component.apply(this, arguments); } Label.prototype.hasContent = function hasContent(children) { var result = false; _react2['default'].Children.forEach(children, function (child) { if (result) { return; } if (child || child === 0) { result = true; } }); return result; }; Label.prototype.render = function render() { var _props = this.props; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['className', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), { // Hack for collapsing on IE8. hidden: !this.hasContent(children) }); return _react2['default'].createElement( 'span', _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), children ); }; return Label; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('label', _utilsBootstrapUtils.bsStyles([].concat(_Object$values(_utilsStyleConfig.State), [_utilsStyleConfig.Style.DEFAULT, _utilsStyleConfig.Style.PRIMARY]), _utilsStyleConfig.Style.DEFAULT, Label)); module.exports = exports['default']; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _ListGroupItem = __webpack_require__(142); var _ListGroupItem2 = _interopRequireDefault(_ListGroupItem); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var propTypes = { /** * You can use a custom element type for this component. * * If not specified, it will be treated as `'li'` if every child is a * non-actionable `<ListGroupItem>`, and `'div'` otherwise. */ componentClass: _reactPropTypesLibElementType2['default'] }; function getDefaultComponent(children) { if (!children) { // FIXME: This is the old behavior. Is this right? return 'div'; } if (_utilsValidComponentChildren2['default'].some(children, function (child) { return child.type !== _ListGroupItem2['default'] || child.props.href || child.props.onClick; })) { return 'div'; } return 'ul'; } var ListGroup = (function (_React$Component) { _inherits(ListGroup, _React$Component); function ListGroup() { _classCallCheck(this, ListGroup); _React$Component.apply(this, arguments); } ListGroup.prototype.render = function render() { var _props = this.props; var children = _props.children; var _props$componentClass = _props.componentClass; var Component = _props$componentClass === undefined ? getDefaultComponent(children) : _props$componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['children', 'componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); var useListItem = Component === 'ul' && _utilsValidComponentChildren2['default'].every(children, function (child) { return child.type === _ListGroupItem2['default']; }); return _react2['default'].createElement( Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), useListItem ? _utilsValidComponentChildren2['default'].map(children, function (child) { return _react.cloneElement(child, { listItem: true }); }) : children ); }; return ListGroup; })(_react2['default'].Component); ListGroup.propTypes = propTypes; exports['default'] = _utilsBootstrapUtils.bsClass('list-group', ListGroup); module.exports = exports['default']; /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _Object$values = __webpack_require__(45)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var propTypes = { active: _react2['default'].PropTypes.any, disabled: _react2['default'].PropTypes.any, header: _react2['default'].PropTypes.node, listItem: _react2['default'].PropTypes.bool, onClick: _react2['default'].PropTypes.func, href: _react2['default'].PropTypes.string, type: _react2['default'].PropTypes.string }; var defaultProps = { listItem: false }; var ListGroupItem = (function (_React$Component) { _inherits(ListGroupItem, _React$Component); function ListGroupItem() { _classCallCheck(this, ListGroupItem); _React$Component.apply(this, arguments); } ListGroupItem.prototype.renderHeader = function renderHeader(header, headingClassName) { if (_react2['default'].isValidElement(header)) { return _react.cloneElement(header, { className: _classnames2['default'](header.props.className, headingClassName) }); } return _react2['default'].createElement( 'h4', { className: headingClassName }, header ); }; ListGroupItem.prototype.render = function render() { var _props = this.props; var active = _props.active; var disabled = _props.disabled; var className = _props.className; var header = _props.header; var listItem = _props.listItem; var children = _props.children; var props = _objectWithoutProperties(_props, ['active', 'disabled', 'className', 'header', 'listItem', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), { active: active, disabled: disabled }); var Component = undefined; if (elementProps.href) { Component = 'a'; } else if (elementProps.onClick) { Component = 'button'; elementProps.type = elementProps.type || 'button'; } else if (listItem) { Component = 'li'; } else { Component = 'span'; } elementProps.className = _classnames2['default'](className, classes); // TODO: Deprecate `header` prop. if (header) { return _react2['default'].createElement( Component, elementProps, this.renderHeader(header, _utilsBootstrapUtils.prefix(bsProps, 'heading')), _react2['default'].createElement( 'p', { className: _utilsBootstrapUtils.prefix(bsProps, 'text') }, children ) ); } return _react2['default'].createElement( Component, elementProps, children ); }; return ListGroupItem; })(_react2['default'].Component); ListGroupItem.propTypes = propTypes; ListGroupItem.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('list-group-item', _utilsBootstrapUtils.bsStyles(_Object$values(_utilsStyleConfig.State), ListGroupItem)); module.exports = exports['default']; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _MediaBody = __webpack_require__(144); var _MediaBody2 = _interopRequireDefault(_MediaBody); var _MediaHeading = __webpack_require__(145); var _MediaHeading2 = _interopRequireDefault(_MediaHeading); var _MediaLeft = __webpack_require__(146); var _MediaLeft2 = _interopRequireDefault(_MediaLeft); var _MediaList = __webpack_require__(147); var _MediaList2 = _interopRequireDefault(_MediaList); var _MediaListItem = __webpack_require__(148); var _MediaListItem2 = _interopRequireDefault(_MediaListItem); var _MediaRight = __webpack_require__(149); var _MediaRight2 = _interopRequireDefault(_MediaRight); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { componentClass: 'div' }; var Media = (function (_React$Component) { _inherits(Media, _React$Component); function Media() { _classCallCheck(this, Media); _React$Component.apply(this, arguments); } Media.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Media; })(_react2['default'].Component); Media.propTypes = propTypes; Media.defaultProps = defaultProps; Media.Heading = _MediaHeading2['default']; Media.Body = _MediaBody2['default']; Media.Left = _MediaLeft2['default']; Media.Right = _MediaRight2['default']; Media.List = _MediaList2['default']; Media.ListItem = _MediaListItem2['default']; exports['default'] = _utilsBootstrapUtils.bsClass('media', Media); module.exports = exports['default']; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { componentClass: 'div' }; var MediaBody = (function (_React$Component) { _inherits(MediaBody, _React$Component); function MediaBody() { _classCallCheck(this, MediaBody); _React$Component.apply(this, arguments); } MediaBody.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return MediaBody; })(_react2['default'].Component); MediaBody.propTypes = propTypes; MediaBody.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('media-body', MediaBody); module.exports = exports['default']; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { componentClass: 'h4' }; var MediaHeading = (function (_React$Component) { _inherits(MediaHeading, _React$Component); function MediaHeading() { _classCallCheck(this, MediaHeading); _React$Component.apply(this, arguments); } MediaHeading.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return MediaHeading; })(_react2['default'].Component); MediaHeading.propTypes = propTypes; MediaHeading.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('media-heading', MediaHeading); module.exports = exports['default']; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Media = __webpack_require__(143); var _Media2 = _interopRequireDefault(_Media); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { /** * Align the media to the top, middle, or bottom of the media object. */ align: _react2['default'].PropTypes.oneOf(['top', 'middle', 'bottom']) }; var MediaLeft = (function (_React$Component) { _inherits(MediaLeft, _React$Component); function MediaLeft() { _classCallCheck(this, MediaLeft); _React$Component.apply(this, arguments); } MediaLeft.prototype.render = function render() { var _props = this.props; var align = _props.align; var className = _props.className; var props = _objectWithoutProperties(_props, ['align', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); if (align) { // The class is e.g. `media-top`, not `media-left-top`. classes[_utilsBootstrapUtils.prefix(_Media2['default'].defaultProps, align)] = true; } return _react2['default'].createElement('div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return MediaLeft; })(_react2['default'].Component); MediaLeft.propTypes = propTypes; exports['default'] = _utilsBootstrapUtils.bsClass('media-left', MediaLeft); module.exports = exports['default']; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var MediaList = (function (_React$Component) { _inherits(MediaList, _React$Component); function MediaList() { _classCallCheck(this, MediaList); _React$Component.apply(this, arguments); } MediaList.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('ul', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return MediaList; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('media-list', MediaList); module.exports = exports['default']; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var MediaListItem = (function (_React$Component) { _inherits(MediaListItem, _React$Component); function MediaListItem() { _classCallCheck(this, MediaListItem); _React$Component.apply(this, arguments); } MediaListItem.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('li', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return MediaListItem; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('media', MediaListItem); module.exports = exports['default']; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Media = __webpack_require__(143); var _Media2 = _interopRequireDefault(_Media); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { /** * Align the media to the top, middle, or bottom of the media object. */ align: _react2['default'].PropTypes.oneOf(['top', 'middle', 'bottom']) }; var MediaRight = (function (_React$Component) { _inherits(MediaRight, _React$Component); function MediaRight() { _classCallCheck(this, MediaRight); _React$Component.apply(this, arguments); } MediaRight.prototype.render = function render() { var _props = this.props; var align = _props.align; var className = _props.className; var props = _objectWithoutProperties(_props, ['align', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); if (align) { // The class is e.g. `media-top`, not `media-right-top`. classes[_utilsBootstrapUtils.prefix(_Media2['default'].defaultProps, align)] = true; } return _react2['default'].createElement('div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return MediaRight; })(_react2['default'].Component); MediaRight.propTypes = propTypes; exports['default'] = _utilsBootstrapUtils.bsClass('media-right', MediaRight); module.exports = exports['default']; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibAll = __webpack_require__(56); var _reactPropTypesLibAll2 = _interopRequireDefault(_reactPropTypesLibAll); var _SafeAnchor = __webpack_require__(51); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var propTypes = { /** * Highlight the menu item as active. */ active: _react2['default'].PropTypes.bool, /** * Disable the menu item, making it unselectable. */ disabled: _react2['default'].PropTypes.bool, /** * Styles the menu item as a horizontal rule, providing visual separation between * groups of menu items. */ divider: _reactPropTypesLibAll2['default'](_react2['default'].PropTypes.bool, function (_ref) { var divider = _ref.divider; var children = _ref.children; return divider && children ? new Error('Children will not be rendered for dividers') : null; }), /** * Value passed to the `onSelect` handler, useful for identifying the selected menu item. */ eventKey: _react2['default'].PropTypes.any, /** * Styles the menu item as a header label, useful for describing a group of menu items. */ header: _react2['default'].PropTypes.bool, /** * HTML `href` attribute corresponding to `a.href`. */ href: _react2['default'].PropTypes.string, /** * Callback fired when the menu item is clicked. */ onClick: _react2['default'].PropTypes.func, /** * Callback fired when the menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: _react2['default'].PropTypes.func }; var defaultProps = { divider: false, disabled: false, header: false }; var MenuItem = (function (_React$Component) { _inherits(MenuItem, _React$Component); function MenuItem(props, context) { _classCallCheck(this, MenuItem); _React$Component.call(this, props, context); this.handleClick = this.handleClick.bind(this); } MenuItem.prototype.handleClick = function handleClick(event) { var _props = this.props; var href = _props.href; var disabled = _props.disabled; var onSelect = _props.onSelect; var eventKey = _props.eventKey; if (!href || disabled) { event.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; MenuItem.prototype.render = function render() { var _props2 = this.props; var active = _props2.active; var disabled = _props2.disabled; var divider = _props2.divider; var header = _props2.header; var onClick = _props2.onClick; var className = _props2.className; var style = _props2.style; var props = _objectWithoutProperties(_props2, ['active', 'disabled', 'divider', 'header', 'onClick', 'className', 'style']); var _splitBsPropsAndOmit = _utilsBootstrapUtils.splitBsPropsAndOmit(props, ['eventKey', 'onSelect']); var bsProps = _splitBsPropsAndOmit[0]; var elementProps = _splitBsPropsAndOmit[1]; if (divider) { // Forcibly blank out the children; separators shouldn't render any. elementProps.children = undefined; return _react2['default'].createElement('li', _extends({}, elementProps, { role: 'separator', className: _classnames2['default'](className, 'divider'), style: style })); } if (header) { return _react2['default'].createElement('li', _extends({}, elementProps, { role: 'heading', className: _classnames2['default'](className, _utilsBootstrapUtils.prefix(bsProps, 'header')), style: style })); } return _react2['default'].createElement( 'li', { role: 'presentation', className: _classnames2['default'](className, { active: active, disabled: disabled }), style: style }, _react2['default'].createElement(_SafeAnchor2['default'], _extends({}, elementProps, { role: 'menuitem', tabIndex: '-1', onClick: _utilsCreateChainedFunction2['default'](onClick, this.handleClick) })) ); }; return MenuItem; })(_react2['default'].Component); MenuItem.propTypes = propTypes; MenuItem.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('dropdown', MenuItem); module.exports = exports['default']; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(20)['default']; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _domHelpersEvents = __webpack_require__(152); var _domHelpersEvents2 = _interopRequireDefault(_domHelpersEvents); var _domHelpersOwnerDocument = __webpack_require__(85); var _domHelpersOwnerDocument2 = _interopRequireDefault(_domHelpersOwnerDocument); var _domHelpersUtilInDOM = __webpack_require__(81); var _domHelpersUtilInDOM2 = _interopRequireDefault(_domHelpersUtilInDOM); var _domHelpersUtilScrollbarSize = __webpack_require__(155); var _domHelpersUtilScrollbarSize2 = _interopRequireDefault(_domHelpersUtilScrollbarSize); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactOverlaysLibModal = __webpack_require__(156); var _reactOverlaysLibModal2 = _interopRequireDefault(_reactOverlaysLibModal); var _reactOverlaysLibUtilsIsOverflowing = __webpack_require__(165); var _reactOverlaysLibUtilsIsOverflowing2 = _interopRequireDefault(_reactOverlaysLibUtilsIsOverflowing); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _Fade = __webpack_require__(127); var _Fade2 = _interopRequireDefault(_Fade); var _ModalBody = __webpack_require__(169); var _ModalBody2 = _interopRequireDefault(_ModalBody); var _ModalDialog = __webpack_require__(170); var _ModalDialog2 = _interopRequireDefault(_ModalDialog); var _ModalFooter = __webpack_require__(171); var _ModalFooter2 = _interopRequireDefault(_ModalFooter); var _ModalHeader = __webpack_require__(172); var _ModalHeader2 = _interopRequireDefault(_ModalHeader); var _ModalTitle = __webpack_require__(173); var _ModalTitle2 = _interopRequireDefault(_ModalTitle); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsSplitComponentProps = __webpack_require__(126); var _utilsSplitComponentProps2 = _interopRequireDefault(_utilsSplitComponentProps); var _utilsStyleConfig = __webpack_require__(41); var propTypes = _extends({}, _reactOverlaysLibModal2['default'].propTypes, _ModalDialog2['default'].propTypes, { /** * Include a backdrop component. Specify 'static' for a backdrop that doesn't * trigger an "onHide" when clicked. */ backdrop: _react2['default'].PropTypes.oneOf(['static', true, false]), /** * Close the modal when escape key is pressed */ keyboard: _react2['default'].PropTypes.bool, /** * Open and close the Modal with a slide and fade animation. */ animation: _react2['default'].PropTypes.bool, /** * A Component type that provides the modal content Markup. This is a useful * prop when you want to use your own styles and markup to create a custom * modal component. */ dialogComponentClass: _reactPropTypesLibElementType2['default'], /** * When `true` The modal will automatically shift focus to itself when it * opens, and replace it to the last focused element when it closes. * Generally this should never be set to false as it makes the Modal less * accessible to assistive technologies, like screen-readers. */ autoFocus: _react2['default'].PropTypes.bool, /** * When `true` The modal will prevent focus from leaving the Modal while * open. Consider leaving the default value here, as it is necessary to make * the Modal work well with assistive technologies, such as screen readers. */ enforceFocus: _react2['default'].PropTypes.bool, /** * When `true` The modal will show itself. */ show: _react2['default'].PropTypes.bool, /** * A callback fired when the header closeButton or non-static backdrop is * clicked. Required if either are specified. */ onHide: _react2['default'].PropTypes.func, /** * Callback fired before the Modal transitions in */ onEnter: _react2['default'].PropTypes.func, /** * Callback fired as the Modal begins to transition in */ onEntering: _react2['default'].PropTypes.func, /** * Callback fired after the Modal finishes transitioning in */ onEntered: _react2['default'].PropTypes.func, /** * Callback fired right before the Modal transitions out */ onExit: _react2['default'].PropTypes.func, /** * Callback fired as the Modal begins to transition out */ onExiting: _react2['default'].PropTypes.func, /** * Callback fired after the Modal finishes transitioning out */ onExited: _react2['default'].PropTypes.func, /** * @private */ container: _reactOverlaysLibModal2['default'].propTypes.container }); var defaultProps = _extends({}, _reactOverlaysLibModal2['default'].defaultProps, { animation: true, dialogComponentClass: _ModalDialog2['default'] }); var childContextTypes = { $bs_modal: _react2['default'].PropTypes.shape({ onHide: _react2['default'].PropTypes.func }) }; var Modal = (function (_React$Component) { _inherits(Modal, _React$Component); function Modal(props, context) { _classCallCheck(this, Modal); _React$Component.call(this, props, context); this.handleEntering = this.handleEntering.bind(this); this.handleExited = this.handleExited.bind(this); this.handleWindowResize = this.handleWindowResize.bind(this); this.handleDialogClick = this.handleDialogClick.bind(this); this.state = { style: {} }; } Modal.prototype.getChildContext = function getChildContext() { return { $bs_modal: { onHide: this.props.onHide } }; }; Modal.prototype.componentWillUnmount = function componentWillUnmount() { // Clean up the listener if we need to. this.handleExited(); }; Modal.prototype.handleEntering = function handleEntering() { // FIXME: This should work even when animation is disabled. _domHelpersEvents2['default'].on(window, 'resize', this.handleWindowResize); this.updateStyle(); }; Modal.prototype.handleExited = function handleExited() { // FIXME: This should work even when animation is disabled. _domHelpersEvents2['default'].off(window, 'resize', this.handleWindowResize); }; Modal.prototype.handleWindowResize = function handleWindowResize() { this.updateStyle(); }; Modal.prototype.handleDialogClick = function handleDialogClick(e) { if (e.target !== e.currentTarget) { return; } this.props.onHide(); }; Modal.prototype.updateStyle = function updateStyle() { if (!_domHelpersUtilInDOM2['default']) { return; } var modalNode = _reactDom2['default'].findDOMNode(this._modal); var modalHeight = modalNode.scrollHeight; var document = _domHelpersOwnerDocument2['default'](modalNode); var bodyIsOverflowing = _reactOverlaysLibUtilsIsOverflowing2['default'](_reactDom2['default'].findDOMNode(this.props.container || document.body)); var modalIsOverflowing = modalHeight > document.documentElement.clientHeight; this.setState({ style: { paddingRight: bodyIsOverflowing && !modalIsOverflowing ? _domHelpersUtilScrollbarSize2['default']() : undefined, paddingLeft: !bodyIsOverflowing && modalIsOverflowing ? _domHelpersUtilScrollbarSize2['default']() : undefined } }); }; Modal.prototype.render = function render() { var _this = this; var _props = this.props; var backdrop = _props.backdrop; var animation = _props.animation; var show = _props.show; var Dialog = _props.dialogComponentClass; var className = _props.className; var style = _props.style; var children = _props.children; var // Just in case this get added to BaseModal propTypes. onEntering = _props.onEntering; var onExited = _props.onExited; var props = _objectWithoutProperties(_props, ['backdrop', 'animation', 'show', 'dialogComponentClass', 'className', 'style', 'children', 'onEntering', 'onExited']); var _splitComponentProps = _utilsSplitComponentProps2['default'](props, _reactOverlaysLibModal2['default']); var baseModalProps = _splitComponentProps[0]; var dialogProps = _splitComponentProps[1]; var inClassName = show && !animation && 'in'; return _react2['default'].createElement( _reactOverlaysLibModal2['default'], _extends({}, baseModalProps, { show: show, onEntering: _utilsCreateChainedFunction2['default'](onEntering, this.handleEntering), onExited: _utilsCreateChainedFunction2['default'](onExited, this.handleExited), backdrop: backdrop, backdropClassName: _classnames2['default'](_utilsBootstrapUtils.prefix(props, 'backdrop'), inClassName), containerClassName: _utilsBootstrapUtils.prefix(props, 'open'), transition: animation ? _Fade2['default'] : undefined, dialogTransitionTimeout: Modal.TRANSITION_DURATION, backdropTransitionTimeout: Modal.BACKDROP_TRANSITION_DURATION }), _react2['default'].createElement( Dialog, _extends({}, dialogProps, { ref: function (c) { _this._modal = c; }, style: _extends({}, this.state.style, style), className: _classnames2['default'](className, inClassName), onClick: backdrop === true ? this.handleDialogClick : null }), children ) ); }; return Modal; })(_react2['default'].Component); Modal.propTypes = propTypes; Modal.defaultProps = defaultProps; Modal.childContextTypes = childContextTypes; Modal.Body = _ModalBody2['default']; Modal.Header = _ModalHeader2['default']; Modal.Title = _ModalTitle2['default']; Modal.Footer = _ModalFooter2['default']; Modal.Dialog = _ModalDialog2['default']; Modal.TRANSITION_DURATION = 300; Modal.BACKDROP_TRANSITION_DURATION = 150; exports['default'] = _utilsBootstrapUtils.bsClass('modal', _utilsBootstrapUtils.bsSizes([_utilsStyleConfig.Size.LARGE, _utilsStyleConfig.Size.SMALL], Modal)); module.exports = exports['default']; /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var on = __webpack_require__(82), off = __webpack_require__(120), filter = __webpack_require__(153); module.exports = { on: on, off: off, filter: filter }; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var contains = __webpack_require__(86), qsa = __webpack_require__(154); module.exports = function (selector, handler) { return function (e) { var top = e.currentTarget, target = e.target, matches = qsa(top, selector); if (matches.some(function (match) { return contains(match, target); })) handler.call(this, e); }; }; /***/ }, /* 154 */ /***/ function(module, exports) { 'use strict'; // Zepto.js // (c) 2010-2015 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. var simpleSelectorRE = /^[\w-]*$/, toArray = Function.prototype.bind.call(Function.prototype.call, [].slice); module.exports = function qsa(element, selector) { var maybeID = selector[0] === '#', maybeClass = selector[0] === '.', nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, isSimple = simpleSelectorRE.test(nameOnly), found; if (isSimple) { if (maybeID) { element = element.getElementById ? element : document; return (found = element.getElementById(nameOnly)) ? [found] : []; } if (element.getElementsByClassName && maybeClass) return toArray(element.getElementsByClassName(nameOnly)); return toArray(element.getElementsByTagName(selector)); } return toArray(element.querySelectorAll(selector)); }; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(81); var size; module.exports = function (recalc) { if (!size || recalc) { if (canUseDOM) { var scrollDiv = document.createElement('div'); scrollDiv.style.position = 'absolute'; scrollDiv.style.top = '-9999px'; scrollDiv.style.width = '50px'; scrollDiv.style.height = '50px'; scrollDiv.style.overflow = 'scroll'; document.body.appendChild(scrollDiv); size = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); } } return size; }; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /*eslint-disable react/prop-types */ var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _mountable = __webpack_require__(157); var _mountable2 = _interopRequireDefault(_mountable); var _elementType = __webpack_require__(52); var _elementType2 = _interopRequireDefault(_elementType); var _Portal = __webpack_require__(158); var _Portal2 = _interopRequireDefault(_Portal); var _ModalManager = __webpack_require__(160); var _ModalManager2 = _interopRequireDefault(_ModalManager); var _ownerDocument = __webpack_require__(122); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _addEventListener = __webpack_require__(119); var _addEventListener2 = _interopRequireDefault(_addEventListener); var _addFocusListener = __webpack_require__(168); var _addFocusListener2 = _interopRequireDefault(_addFocusListener); var _inDOM = __webpack_require__(81); var _inDOM2 = _interopRequireDefault(_inDOM); var _activeElement = __webpack_require__(84); var _activeElement2 = _interopRequireDefault(_activeElement); var _contains = __webpack_require__(86); var _contains2 = _interopRequireDefault(_contains); var _getContainer = __webpack_require__(159); var _getContainer2 = _interopRequireDefault(_getContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var modalManager = new _ModalManager2.default(); /** * Love them or hate them, `<Modal/>` provides a solid foundation for creating dialogs, lightboxes, or whatever else. * The Modal component renders its `children` node in front of a backdrop component. * * The Modal offers a few helpful features over using just a `<Portal/>` component and some styles: * * - Manages dialog stacking when one-at-a-time just isn't enough. * - Creates a backdrop, for disabling interaction below the modal. * - It properly manages focus; moving to the modal content, and keeping it there until the modal is closed. * - It disables scrolling of the page content while open. * - Adds the appropriate ARIA roles are automatically. * - Easily pluggable animations via a `<Transition/>` component. * * Note that, in the same way the backdrop element prevents users from clicking or interacting * with the page content underneath the Modal, Screen readers also need to be signaled to not to * interact with page content while the Modal is open. To do this, we use a common technique of applying * the `aria-hidden='true'` attribute to the non-Modal elements in the Modal `container`. This means that for * a Modal to be truly modal, it should have a `container` that is _outside_ your app's * React hierarchy (such as the default: document.body). */ var Modal = _react2.default.createClass({ displayName: 'Modal', propTypes: _extends({}, _Portal2.default.propTypes, { /** * Set the visibility of the Modal */ show: _react2.default.PropTypes.bool, /** * A Node, Component instance, or function that returns either. The Modal is appended to it's container element. * * For the sake of assistive technologies, the container should usually be the document body, so that the rest of the * page content can be placed behind a virtual backdrop as well as a visual one. */ container: _react2.default.PropTypes.oneOfType([_mountable2.default, _react2.default.PropTypes.func]), /** * A callback fired when the Modal is opening. */ onShow: _react2.default.PropTypes.func, /** * A callback fired when either the backdrop is clicked, or the escape key is pressed. * * The `onHide` callback only signals intent from the Modal, * you must actually set the `show` prop to `false` for the Modal to close. */ onHide: _react2.default.PropTypes.func, /** * Include a backdrop component. */ backdrop: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.bool, _react2.default.PropTypes.oneOf(['static'])]), /** * A callback fired when the escape key, if specified in `keyboard`, is pressed. */ onEscapeKeyUp: _react2.default.PropTypes.func, /** * A callback fired when the backdrop, if specified, is clicked. */ onBackdropClick: _react2.default.PropTypes.func, /** * A style object for the backdrop component. */ backdropStyle: _react2.default.PropTypes.object, /** * A css class or classes for the backdrop component. */ backdropClassName: _react2.default.PropTypes.string, /** * A css class or set of classes applied to the modal container when the modal is open, * and removed when it is closed. */ containerClassName: _react2.default.PropTypes.string, /** * Close the modal when escape key is pressed */ keyboard: _react2.default.PropTypes.bool, /** * A `<Transition/>` component to use for the dialog and backdrop components. */ transition: _elementType2.default, /** * The `timeout` of the dialog transition if specified. This number is used to ensure that * transition callbacks are always fired, even if browser transition events are canceled. * * See the Transition `timeout` prop for more infomation. */ dialogTransitionTimeout: _react2.default.PropTypes.number, /** * The `timeout` of the backdrop transition if specified. This number is used to * ensure that transition callbacks are always fired, even if browser transition events are canceled. * * See the Transition `timeout` prop for more infomation. */ backdropTransitionTimeout: _react2.default.PropTypes.number, /** * When `true` The modal will automatically shift focus to itself when it opens, and * replace it to the last focused element when it closes. This also * works correctly with any Modal children that have the `autoFocus` prop. * * Generally this should never be set to `false` as it makes the Modal less * accessible to assistive technologies, like screen readers. */ autoFocus: _react2.default.PropTypes.bool, /** * When `true` The modal will prevent focus from leaving the Modal while open. * * Generally this should never be set to `false` as it makes the Modal less * accessible to assistive technologies, like screen readers. */ enforceFocus: _react2.default.PropTypes.bool, /** * Callback fired before the Modal transitions in */ onEnter: _react2.default.PropTypes.func, /** * Callback fired as the Modal begins to transition in */ onEntering: _react2.default.PropTypes.func, /** * Callback fired after the Modal finishes transitioning in */ onEntered: _react2.default.PropTypes.func, /** * Callback fired right before the Modal transitions out */ onExit: _react2.default.PropTypes.func, /** * Callback fired as the Modal begins to transition out */ onExiting: _react2.default.PropTypes.func, /** * Callback fired after the Modal finishes transitioning out */ onExited: _react2.default.PropTypes.func }), getDefaultProps: function getDefaultProps() { var noop = function noop() {}; return { show: false, backdrop: true, keyboard: true, autoFocus: true, enforceFocus: true, onHide: noop }; }, getInitialState: function getInitialState() { return { exited: !this.props.show }; }, render: function render() { var _props = this.props; var show = _props.show; var container = _props.container; var children = _props.children; var Transition = _props.transition; var backdrop = _props.backdrop; var dialogTransitionTimeout = _props.dialogTransitionTimeout; var className = _props.className; var style = _props.style; var onExit = _props.onExit; var onExiting = _props.onExiting; var onEnter = _props.onEnter; var onEntering = _props.onEntering; var onEntered = _props.onEntered; var dialog = _react2.default.Children.only(children); var mountModal = show || Transition && !this.state.exited; if (!mountModal) { return null; } var _dialog$props = dialog.props; var role = _dialog$props.role; var tabIndex = _dialog$props.tabIndex; if (role === undefined || tabIndex === undefined) { dialog = (0, _react.cloneElement)(dialog, { role: role === undefined ? 'document' : role, tabIndex: tabIndex == null ? '-1' : tabIndex }); } if (Transition) { dialog = _react2.default.createElement( Transition, { transitionAppear: true, unmountOnExit: true, 'in': show, timeout: dialogTransitionTimeout, onExit: onExit, onExiting: onExiting, onExited: this.handleHidden, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered }, dialog ); } return _react2.default.createElement( _Portal2.default, { ref: this.setMountNode, container: container }, _react2.default.createElement( 'div', { ref: 'modal', role: role || 'dialog', style: style, className: className }, backdrop && this.renderBackdrop(), dialog ) ); }, renderBackdrop: function renderBackdrop() { var _props2 = this.props; var Transition = _props2.transition; var backdropTransitionTimeout = _props2.backdropTransitionTimeout; var backdrop = _react2.default.createElement('div', { ref: 'backdrop', style: this.props.backdropStyle, className: this.props.backdropClassName, onClick: this.handleBackdropClick }); if (Transition) { backdrop = _react2.default.createElement( Transition, { transitionAppear: true, 'in': this.props.show, timeout: backdropTransitionTimeout }, backdrop ); } return backdrop; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.show) { this.setState({ exited: false }); } else if (!nextProps.transition) { // Otherwise let handleHidden take care of marking exited. this.setState({ exited: true }); } }, componentWillUpdate: function componentWillUpdate(nextProps) { if (!this.props.show && nextProps.show) { this.checkForFocus(); } }, componentDidMount: function componentDidMount() { if (this.props.show) { this.onShow(); } }, componentDidUpdate: function componentDidUpdate(prevProps) { var transition = this.props.transition; if (prevProps.show && !this.props.show && !transition) { // Otherwise handleHidden will call this. this.onHide(); } else if (!prevProps.show && this.props.show) { this.onShow(); } }, componentWillUnmount: function componentWillUnmount() { var _props3 = this.props; var show = _props3.show; var transition = _props3.transition; if (show || transition && !this.state.exited) { this.onHide(); } }, onShow: function onShow() { var doc = (0, _ownerDocument2.default)(this); var container = (0, _getContainer2.default)(this.props.container, doc.body); modalManager.add(this, container, this.props.containerClassName); this._onDocumentKeyupListener = (0, _addEventListener2.default)(doc, 'keyup', this.handleDocumentKeyUp); this._onFocusinListener = (0, _addFocusListener2.default)(this.enforceFocus); this.focus(); if (this.props.onShow) { this.props.onShow(); } }, onHide: function onHide() { modalManager.remove(this); this._onDocumentKeyupListener.remove(); this._onFocusinListener.remove(); this.restoreLastFocus(); }, setMountNode: function setMountNode(ref) { this.mountNode = ref ? ref.getMountNode() : ref; }, handleHidden: function handleHidden() { this.setState({ exited: true }); this.onHide(); if (this.props.onExited) { var _props4; (_props4 = this.props).onExited.apply(_props4, arguments); } }, handleBackdropClick: function handleBackdropClick(e) { if (e.target !== e.currentTarget) { return; } if (this.props.onBackdropClick) { this.props.onBackdropClick(e); } if (this.props.backdrop === true) { this.props.onHide(); } }, handleDocumentKeyUp: function handleDocumentKeyUp(e) { if (this.props.keyboard && e.keyCode === 27 && this.isTopModal()) { if (this.props.onEscapeKeyUp) { this.props.onEscapeKeyUp(e); } this.props.onHide(); } }, checkForFocus: function checkForFocus() { if (_inDOM2.default) { this.lastFocus = (0, _activeElement2.default)(); } }, focus: function focus() { var autoFocus = this.props.autoFocus; var modalContent = this.getDialogElement(); var current = (0, _activeElement2.default)((0, _ownerDocument2.default)(this)); var focusInModal = current && (0, _contains2.default)(modalContent, current); if (modalContent && autoFocus && !focusInModal) { this.lastFocus = current; if (!modalContent.hasAttribute('tabIndex')) { modalContent.setAttribute('tabIndex', -1); (0, _warning2.default)(false, 'The modal content node does not accept focus. ' + 'For the benefit of assistive technologies, the tabIndex of the node is being set to "-1".'); } modalContent.focus(); } }, restoreLastFocus: function restoreLastFocus() { // Support: <=IE11 doesn't support `focus()` on svg elements (RB: #917) if (this.lastFocus && this.lastFocus.focus) { this.lastFocus.focus(); this.lastFocus = null; } }, enforceFocus: function enforceFocus() { var enforceFocus = this.props.enforceFocus; if (!enforceFocus || !this.isMounted() || !this.isTopModal()) { return; } var active = (0, _activeElement2.default)((0, _ownerDocument2.default)(this)); var modal = this.getDialogElement(); if (modal && modal !== active && !(0, _contains2.default)(modal, active)) { modal.focus(); } }, //instead of a ref, which might conflict with one the parent applied. getDialogElement: function getDialogElement() { var node = this.refs.modal; return node && node.lastChild; }, isTopModal: function isTopModal() { return modalManager.isTopModal(this); } }); Modal.manager = modalManager; exports.default = Modal; module.exports = exports['default']; /***/ }, /* 157 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _common = __webpack_require__(53); /** * Checks whether a prop provides a DOM element * * The element can be provided in two forms: * - Directly passed * - Or passed an object that has a `render` method * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ function validate(props, propName, componentName) { if (typeof props[propName] !== 'object' || typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) { return new Error(_common.errMsg(props, propName, componentName, ', expected a DOM element or an object that has a `render` method')); } } exports['default'] = _common.createChainableTypeChecker(validate); module.exports = exports['default']; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _mountable = __webpack_require__(157); var _mountable2 = _interopRequireDefault(_mountable); var _ownerDocument = __webpack_require__(122); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _getContainer = __webpack_require__(159); var _getContainer2 = _interopRequireDefault(_getContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ var Portal = _react2.default.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: _react2.default.PropTypes.oneOfType([_mountable2.default, _react2.default.PropTypes.func]) }, componentDidMount: function componentDidMount() { this._renderOverlay(); }, componentDidUpdate: function componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = (0, _getContainer2.default)(nextProps.container, (0, _ownerDocument2.default)(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount: function componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget: function _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); this._portalContainerNode = (0, _getContainer2.default)(this.props.container, (0, _ownerDocument2.default)(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget: function _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay: function _renderOverlay() { var overlay = !this.props.children ? null : _react2.default.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = _reactDom2.default.unstable_renderSubtreeIntoContainer(this, overlay, this._overlayTarget); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay: function _unrenderOverlay() { if (this._overlayTarget) { _reactDom2.default.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render: function render() { return null; }, getMountNode: function getMountNode() { return this._overlayTarget; }, getOverlayDOMNode: function getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { if (this._overlayInstance.getWrappedDOMNode) { return this._overlayInstance.getWrappedDOMNode(); } else { return _reactDom2.default.findDOMNode(this._overlayInstance); } } return null; } }); exports.default = Portal; module.exports = exports['default']; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getContainer; var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getContainer(container, defaultContainer) { container = typeof container === 'function' ? container() : container; return _reactDom2.default.findDOMNode(container) || defaultContainer; } module.exports = exports['default']; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _style = __webpack_require__(71); var _style2 = _interopRequireDefault(_style); var _class = __webpack_require__(161); var _class2 = _interopRequireDefault(_class); var _scrollbarSize = __webpack_require__(155); var _scrollbarSize2 = _interopRequireDefault(_scrollbarSize); var _isOverflowing = __webpack_require__(165); var _isOverflowing2 = _interopRequireDefault(_isOverflowing); var _manageAriaHidden = __webpack_require__(167); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function findIndexOf(arr, cb) { var idx = -1; arr.some(function (d, i) { if (cb(d, i)) { idx = i; return true; } }); return idx; } function findContainer(data, modal) { return findIndexOf(data, function (d) { return d.modals.indexOf(modal) !== -1; }); } /** * Proper state managment for containers and the modals in those containers. * * @internal Used by the Modal to ensure proper styling of containers. */ var ModalManager = function () { function ModalManager() { var hideSiblingNodes = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; _classCallCheck(this, ModalManager); this.hideSiblingNodes = hideSiblingNodes; this.modals = []; this.containers = []; this.data = []; } _createClass(ModalManager, [{ key: 'add', value: function add(modal, container, className) { var modalIdx = this.modals.indexOf(modal); var containerIdx = this.containers.indexOf(container); if (modalIdx !== -1) { return modalIdx; } modalIdx = this.modals.length; this.modals.push(modal); if (this.hideSiblingNodes) { (0, _manageAriaHidden.hideSiblings)(container, modal.mountNode); } if (containerIdx !== -1) { this.data[containerIdx].modals.push(modal); return modalIdx; } var data = { modals: [modal], //right now only the first modal of a container will have its classes applied classes: className ? className.split(/\s+/) : [], //we are only interested in the actual `style` here becasue we will override it style: { overflow: container.style.overflow, paddingRight: container.style.paddingRight } }; var style = { overflow: 'hidden' }; data.overflowing = (0, _isOverflowing2.default)(container); if (data.overflowing) { // use computed style, here to get the real padding // to add our scrollbar width style.paddingRight = parseInt((0, _style2.default)(container, 'paddingRight') || 0, 10) + (0, _scrollbarSize2.default)() + 'px'; } (0, _style2.default)(container, style); data.classes.forEach(_class2.default.addClass.bind(null, container)); this.containers.push(container); this.data.push(data); return modalIdx; } }, { key: 'remove', value: function remove(modal) { var modalIdx = this.modals.indexOf(modal); if (modalIdx === -1) { return; } var containerIdx = findContainer(this.data, modal); var data = this.data[containerIdx]; var container = this.containers[containerIdx]; data.modals.splice(data.modals.indexOf(modal), 1); this.modals.splice(modalIdx, 1); // if that was the last modal in a container, // clean up the container stylinhg. if (data.modals.length === 0) { Object.keys(data.style).forEach(function (key) { return container.style[key] = data.style[key]; }); data.classes.forEach(_class2.default.removeClass.bind(null, container)); if (this.hideSiblingNodes) { (0, _manageAriaHidden.showSiblings)(container, modal.mountNode); } this.containers.splice(containerIdx, 1); this.data.splice(containerIdx, 1); } else if (this.hideSiblingNodes) { //otherwise make sure the next top modal is visible to a SR (0, _manageAriaHidden.ariaHidden)(false, data.modals[data.modals.length - 1].mountNode); } } }, { key: 'isTopModal', value: function isTopModal(modal) { return !!this.modals.length && this.modals[this.modals.length - 1] === modal; } }]); return ModalManager; }(); exports.default = ModalManager; module.exports = exports['default']; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = { addClass: __webpack_require__(162), removeClass: __webpack_require__(164), hasClass: __webpack_require__(163) }; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var hasClass = __webpack_require__(163); module.exports = function addClass(element, className) { if (element.classList) element.classList.add(className);else if (!hasClass(element)) element.className = element.className + ' ' + className; }; /***/ }, /* 163 */ /***/ function(module, exports) { 'use strict'; module.exports = function hasClass(element, className) { if (element.classList) return !!className && element.classList.contains(className);else return (' ' + element.className + ' ').indexOf(' ' + className + ' ') !== -1; }; /***/ }, /* 164 */ /***/ function(module, exports) { 'use strict'; module.exports = function removeClass(element, className) { if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ''); }; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isOverflowing; var _isWindow = __webpack_require__(166); var _isWindow2 = _interopRequireDefault(_isWindow); var _ownerDocument = __webpack_require__(85); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isBody(node) { return node && node.tagName.toLowerCase() === 'body'; } function bodyIsOverflowing(node) { var doc = (0, _ownerDocument2.default)(node); var win = (0, _isWindow2.default)(doc); var fullWidth = win.innerWidth; // Support: ie8, no innerWidth if (!fullWidth) { var documentElementRect = doc.documentElement.getBoundingClientRect(); fullWidth = documentElementRect.right - Math.abs(documentElementRect.left); } return doc.body.clientWidth < fullWidth; } function isOverflowing(container) { var win = (0, _isWindow2.default)(container); return win || isBody(container) ? bodyIsOverflowing(container) : container.scrollHeight > container.clientHeight; } module.exports = exports['default']; /***/ }, /* 166 */ /***/ function(module, exports) { 'use strict'; module.exports = function getWindow(node) { return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false; }; /***/ }, /* 167 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ariaHidden = ariaHidden; exports.hideSiblings = hideSiblings; exports.showSiblings = showSiblings; var BLACKLIST = ['template', 'script', 'style']; var isHidable = function isHidable(_ref) { var nodeType = _ref.nodeType; var tagName = _ref.tagName; return nodeType === 1 && BLACKLIST.indexOf(tagName.toLowerCase()) === -1; }; var siblings = function siblings(container, mount, cb) { mount = [].concat(mount); [].forEach.call(container.children, function (node) { if (mount.indexOf(node) === -1 && isHidable(node)) { cb(node); } }); }; function ariaHidden(show, node) { if (!node) { return; } if (show) { node.setAttribute('aria-hidden', 'true'); } else { node.removeAttribute('aria-hidden'); } } function hideSiblings(container, mountNode) { siblings(container, mountNode, function (node) { return ariaHidden(true, node); }); } function showSiblings(container, mountNode) { siblings(container, mountNode, function (node) { return ariaHidden(false, node); }); } /***/ }, /* 168 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addFocusListener; /** * Firefox doesn't have a focusin event so using capture is easiest way to get bubbling * IE8 can't do addEventListener, but does have onfocusin, so we use that in ie8 * * We only allow one Listener at a time to avoid stack overflows */ function addFocusListener(handler) { var useFocusin = !document.addEventListener; var remove = void 0; if (useFocusin) { document.attachEvent('onfocusin', handler); remove = function remove() { return document.detachEvent('onfocusin', handler); }; } else { document.addEventListener('focus', handler, true); remove = function remove() { return document.removeEventListener('focus', handler, true); }; } return { remove: remove }; } module.exports = exports['default']; /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var ModalBody = (function (_React$Component) { _inherits(ModalBody, _React$Component); function ModalBody() { _classCallCheck(this, ModalBody); _React$Component.apply(this, arguments); } ModalBody.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return ModalBody; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('modal-body', ModalBody); module.exports = exports['default']; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var propTypes = { /** * A css class to apply to the Modal dialog DOM node. */ dialogClassName: _react2['default'].PropTypes.string }; var ModalDialog = (function (_React$Component) { _inherits(ModalDialog, _React$Component); function ModalDialog() { _classCallCheck(this, ModalDialog); _React$Component.apply(this, arguments); } ModalDialog.prototype.render = function render() { var _extends2; var _props = this.props; var dialogClassName = _props.dialogClassName; var className = _props.className; var style = _props.style; var children = _props.children; var props = _objectWithoutProperties(_props, ['dialogClassName', 'className', 'style', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var bsClassName = _utilsBootstrapUtils.prefix(bsProps); var modalStyle = _extends({ display: 'block' }, style); var dialogClasses = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[bsClassName] = false, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'dialog')] = true, _extends2)); return _react2['default'].createElement( 'div', _extends({}, elementProps, { tabIndex: '-1', role: 'dialog', style: modalStyle, className: _classnames2['default'](className, bsClassName) }), _react2['default'].createElement( 'div', { className: _classnames2['default'](dialogClassName, dialogClasses) }, _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils.prefix(bsProps, 'content'), role: 'document' }, children ) ) ); }; return ModalDialog; })(_react2['default'].Component); ModalDialog.propTypes = propTypes; exports['default'] = _utilsBootstrapUtils.bsClass('modal', _utilsBootstrapUtils.bsSizes([_utilsStyleConfig.Size.LARGE, _utilsStyleConfig.Size.SMALL], ModalDialog)); module.exports = exports['default']; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var ModalFooter = (function (_React$Component) { _inherits(ModalFooter, _React$Component); function ModalFooter() { _classCallCheck(this, ModalFooter); _React$Component.apply(this, arguments); } ModalFooter.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return ModalFooter; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('modal-footer', ModalFooter); module.exports = exports['default']; /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); // TODO: `aria-label` should be `closeLabel`. var propTypes = { /** * The 'aria-label' attribute provides an accessible label for the close * button. It is used for Assistive Technology when the label text is not * readable. */ 'aria-label': _react2['default'].PropTypes.string, /** * Specify whether the Component should contain a close button */ closeButton: _react2['default'].PropTypes.bool, /** * A Callback fired when the close button is clicked. If used directly inside * a Modal component, the onHide will automatically be propagated up to the * parent Modal `onHide`. */ onHide: _react2['default'].PropTypes.func }; var defaultProps = { 'aria-label': 'Close', closeButton: false }; var contextTypes = { $bs_modal: _react2['default'].PropTypes.shape({ onHide: _react2['default'].PropTypes.func }) }; var ModalHeader = (function (_React$Component) { _inherits(ModalHeader, _React$Component); function ModalHeader() { _classCallCheck(this, ModalHeader); _React$Component.apply(this, arguments); } ModalHeader.prototype.render = function render() { var _props = this.props; var label = _props['aria-label']; var closeButton = _props.closeButton; var onHide = _props.onHide; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['aria-label', 'closeButton', 'onHide', 'className', 'children']); var modal = this.context.$bs_modal; var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement( 'div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), closeButton && _react2['default'].createElement( 'button', { type: 'button', className: 'close', 'aria-label': label, onClick: _utilsCreateChainedFunction2['default'](modal.onHide, onHide) }, _react2['default'].createElement( 'span', { 'aria-hidden': 'true' }, '×' ) ), children ); }; return ModalHeader; })(_react2['default'].Component); ModalHeader.propTypes = propTypes; ModalHeader.defaultProps = defaultProps; ModalHeader.contextTypes = contextTypes; exports['default'] = _utilsBootstrapUtils.bsClass('modal-header', ModalHeader); module.exports = exports['default']; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var ModalTitle = (function (_React$Component) { _inherits(ModalTitle, _React$Component); function ModalTitle() { _classCallCheck(this, ModalTitle); _React$Component.apply(this, arguments); } ModalTitle.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('h4', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return ModalTitle; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('modal-title', ModalTitle); module.exports = exports['default']; /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _keycode = __webpack_require__(87); var _keycode2 = _interopRequireDefault(_keycode); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactPropTypesLibAll = __webpack_require__(56); var _reactPropTypesLibAll2 = _interopRequireDefault(_reactPropTypesLibAll); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); // TODO: Should we expose `<NavItem>` as `<Nav.Item>`? // TODO: This `bsStyle` is very unlike the others. Should we rename it? // TODO: `pullRight` and `pullLeft` don't render right outside of `navbar`. // Consider renaming or replacing them. var propTypes = { /** * Marks the NavItem with a matching `eventKey` as active. Has a * higher precedence over `activeHref`. */ activeKey: _react2['default'].PropTypes.any, /** * Marks the child NavItem with a matching `href` prop as active. */ activeHref: _react2['default'].PropTypes.string, /** * NavItems are be positioned vertically. */ stacked: _react2['default'].PropTypes.bool, justified: _reactPropTypesLibAll2['default'](_react2['default'].PropTypes.bool, function (_ref) { var justified = _ref.justified; var navbar = _ref.navbar; return justified && navbar ? Error('justified navbar `Nav`s are not supported') : null; }), /** * A callback fired when a NavItem is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` */ onSelect: _react2['default'].PropTypes.func, /** * ARIA role for the Nav, in the context of a TabContainer, the default will * be set to "tablist", but can be overridden by the Nav when set explicitly. * * When the role is set to "tablist" NavItem focus is managed according to * the ARIA authoring practices for tabs: * https://www.w3.org/TR/2013/WD-wai-aria-practices-20130307/#tabpanel */ role: _react2['default'].PropTypes.string, /** * Apply styling an alignment for use in a Navbar. This prop will be set * automatically when the Nav is used inside a Navbar. */ navbar: _react2['default'].PropTypes.bool, /** * Float the Nav to the right. When `navbar` is `true` the appropriate * contextual classes are added as well. */ pullRight: _react2['default'].PropTypes.bool, /** * Float the Nav to the left. When `navbar` is `true` the appropriate * contextual classes are added as well. */ pullLeft: _react2['default'].PropTypes.bool }; var defaultProps = { justified: false, pullRight: false, pullLeft: false, stacked: false }; var contextTypes = { $bs_navbar: _react2['default'].PropTypes.shape({ bsClass: _react2['default'].PropTypes.string }), $bs_tabContainer: _react2['default'].PropTypes.shape({ activeKey: _react2['default'].PropTypes.any, onSelect: _react2['default'].PropTypes.func.isRequired, getTabId: _react2['default'].PropTypes.func.isRequired, getPaneId: _react2['default'].PropTypes.func.isRequired }) }; var Nav = (function (_React$Component) { _inherits(Nav, _React$Component); function Nav() { _classCallCheck(this, Nav); _React$Component.apply(this, arguments); } Nav.prototype.componentDidUpdate = function componentDidUpdate() { var _this = this; if (!this._needsRefocus) { return; } this._needsRefocus = false; var children = this.props.children; var activeChild = _utilsValidComponentChildren2['default'].find(children, function (child) { return _this.isChildActive(child); }); var childrenArray = _utilsValidComponentChildren2['default'].toArray(children); var activeChildIndex = childrenArray.indexOf(activeChild); var childNodes = _reactDom2['default'].findDOMNode(this).children; var activeNode = childNodes && childNodes[activeChildIndex]; if (!activeNode || !activeNode.firstChild) { return; } activeNode.firstChild.focus(); }; Nav.prototype.handleTabKeyDown = function handleTabKeyDown(onSelect, event) { var nextActiveChild = undefined; switch (event.keyCode) { case _keycode2['default'].codes.left: case _keycode2['default'].codes.up: nextActiveChild = this.getNextActiveChild(-1); break; case _keycode2['default'].codes.right: case _keycode2['default'].codes.down: nextActiveChild = this.getNextActiveChild(1); break; default: // It was a different key; don't handle this keypress. return; } event.preventDefault(); if (onSelect && nextActiveChild && nextActiveChild.props.eventKey) { onSelect(nextActiveChild.props.eventKey); } this._needsRefocus = true; }; Nav.prototype.getNextActiveChild = function getNextActiveChild(offset) { var _this2 = this; var children = this.props.children; var validChildren = children.filter(function (child) { return child.props.eventKey && !child.props.disabled; }); var activeChild = _utilsValidComponentChildren2['default'].find(children, function (child) { return _this2.isChildActive(child); }); // This assumes the active child is not disabled. var activeChildIndex = validChildren.indexOf(activeChild); if (activeChildIndex === -1) { // Something has gone wrong. Select the first valid child we can find. return validChildren[0]; } var nextIndex = activeChildIndex + offset; var numValidChildren = validChildren.length; if (nextIndex >= numValidChildren) { nextIndex = 0; } else if (nextIndex < 0) { nextIndex = numValidChildren - 1; } return validChildren[nextIndex]; }; Nav.prototype.isChildActive = function isChildActive(child) { var _props = this.props; var activeKey = _props.activeKey; var activeHref = _props.activeHref; var tabContainer = this.context.$bs_tabContainer; if (tabContainer) { var childKey = child.props.eventKey; true ? _warning2['default'](!child.props.active, 'Specifying a `<NavItem>` `active` prop in the context of a ' + '`<TabContainer>` is not supported. Instead use `<TabContainer ' + ('activeKey={' + childKey + '} />`')) : undefined; var active = childKey === tabContainer.activeKey; // Only warn on the active child to avoid spamming the console. true ? _warning2['default'](!active || activeKey == null && !activeHref, 'Specifying a `<Nav>` `activeKey` or `activeHref` in the context of ' + 'a `<TabContainer>` is not supported. Instead use `<TabContainer ' + ('activeKey={' + childKey + '} />`')) : undefined; return active; } if (child.props.active) { return true; } if (activeKey != null && child.props.eventKey === activeKey) { return true; } if (activeHref && child.props.href === activeHref) { return true; } return child.props.active; }; Nav.prototype.getTabProps = function getTabProps(child, tabContainer, navRole, active, onSelect) { var _this3 = this; if (!tabContainer && navRole !== 'tablist') { // No tab props here. return null; } var _child$props = child.props; var id = _child$props.id; var controls = _child$props['aria-controls']; var eventKey = _child$props.eventKey; var role = _child$props.role; var onKeyDown = _child$props.onKeyDown; var tabIndex = _child$props.tabIndex; if (tabContainer) { true ? _warning2['default'](!id && !controls, 'In the context of a `<TabContainer>`, `<NavItem>`s are given ' + 'generated `id` and `aria-controls` attributes for the sake of ' + 'proper component accessibility. Any provided ones will be ignored. ' + 'To control these attributes directly, provide a `generateChildId` ' + 'prop to the parent `<TabContainer>`.') : undefined; id = tabContainer.getTabId(eventKey); controls = tabContainer.getPaneId(eventKey); } if (navRole === 'tablist') { role = role || 'tab'; onKeyDown = _utilsCreateChainedFunction2['default'](function (event) { return _this3.handleTabKeyDown(onSelect, event); }, onKeyDown); tabIndex = active ? tabIndex : -1; } return { id: id, role: role, onKeyDown: onKeyDown, 'aria-controls': controls, tabIndex: tabIndex }; }; Nav.prototype.render = function render() { var _extends2, _this4 = this; var _props2 = this.props; var activeKey = _props2.activeKey; var activeHref = _props2.activeHref; var stacked = _props2.stacked; var justified = _props2.justified; var onSelect = _props2.onSelect; var propsRole = _props2.role; var propsNavbar = _props2.navbar; var pullRight = _props2.pullRight; var pullLeft = _props2.pullLeft; var className = _props2.className; var children = _props2.children; var props = _objectWithoutProperties(_props2, ['activeKey', 'activeHref', 'stacked', 'justified', 'onSelect', 'role', 'navbar', 'pullRight', 'pullLeft', 'className', 'children']); var tabContainer = this.context.$bs_tabContainer; var role = propsRole || (tabContainer ? 'tablist' : null); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'stacked')] = stacked, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'justified')] = justified, _extends2)); var navbar = propsNavbar != null ? propsNavbar : this.context.$bs_navbar; var pullLeftClassName = undefined; var pullRightClassName = undefined; if (navbar) { var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; classes[_utilsBootstrapUtils.prefix(navbarProps, 'nav')] = true; pullRightClassName = _utilsBootstrapUtils.prefix(navbarProps, 'right'); pullLeftClassName = _utilsBootstrapUtils.prefix(navbarProps, 'left'); } else { pullRightClassName = 'pull-right'; pullLeftClassName = 'pull-left'; } classes[pullRightClassName] = pullRight; classes[pullLeftClassName] = pullLeft; return _react2['default'].createElement( 'ul', _extends({}, elementProps, { role: role, className: _classnames2['default'](className, classes) }), _utilsValidComponentChildren2['default'].map(children, function (child) { var active = _this4.isChildActive(child); var childOnSelect = _utilsCreateChainedFunction2['default'](child.props.onSelect, onSelect, tabContainer && tabContainer.onSelect); return _react.cloneElement(child, _extends({}, _this4.getTabProps(child, tabContainer, role, active, childOnSelect), { active: active, activeKey: activeKey, activeHref: activeHref, onSelect: childOnSelect })); }) ); }; return Nav; })(_react2['default'].Component); Nav.propTypes = propTypes; Nav.defaultProps = defaultProps; Nav.contextTypes = contextTypes; exports['default'] = _utilsBootstrapUtils.bsClass('nav', _utilsBootstrapUtils.bsStyles(['tabs', 'pills'], Nav)); module.exports = exports['default']; /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { // TODO: Remove this pragma once we upgrade eslint-config-airbnb. /* eslint-disable react/no-multi-comp */ 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _uncontrollable = __webpack_require__(89); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _Grid = __webpack_require__(133); var _Grid2 = _interopRequireDefault(_Grid); var _NavbarBrand = __webpack_require__(176); var _NavbarBrand2 = _interopRequireDefault(_NavbarBrand); var _NavbarCollapse = __webpack_require__(177); var _NavbarCollapse2 = _interopRequireDefault(_NavbarCollapse); var _NavbarHeader = __webpack_require__(178); var _NavbarHeader2 = _interopRequireDefault(_NavbarHeader); var _NavbarToggle = __webpack_require__(179); var _NavbarToggle2 = _interopRequireDefault(_NavbarToggle); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var propTypes = { /** * Create a fixed navbar along the top of the screen, that scrolls with the * page */ fixedTop: _react2['default'].PropTypes.bool, /** * Create a fixed navbar along the bottom of the screen, that scrolls with * the page */ fixedBottom: _react2['default'].PropTypes.bool, /** * Create a full-width navbar that scrolls away with the page */ staticTop: _react2['default'].PropTypes.bool, /** * An alternative dark visual style for the Navbar */ inverse: _react2['default'].PropTypes.bool, /** * Allow the Navbar to fluidly adjust to the page or container width, instead * of at the predefined screen breakpoints */ fluid: _react2['default'].PropTypes.bool, /** * Set a custom element for this component. */ componentClass: _reactPropTypesLibElementType2['default'], /** * A callback fired when the `<Navbar>` body collapses or expands. Fired when * a `<Navbar.Toggle>` is clicked and called with the new `navExpanded` * boolean value. * * @controllable navExpanded */ onToggle: _react2['default'].PropTypes.func, /** * Explicitly set the visiblity of the navbar body * * @controllable onToggle */ expanded: _react2['default'].PropTypes.bool, role: _react2['default'].PropTypes.string }; var defaultProps = { componentClass: 'nav', fixedTop: false, fixedBottom: false, staticTop: false, inverse: false, fluid: false }; var childContextTypes = { $bs_navbar: _react.PropTypes.shape({ bsClass: _react.PropTypes.string, expanded: _react.PropTypes.bool, onToggle: _react.PropTypes.func.isRequired }) }; var Navbar = (function (_React$Component) { _inherits(Navbar, _React$Component); function Navbar(props, context) { _classCallCheck(this, Navbar); _React$Component.call(this, props, context); this.handleToggle = this.handleToggle.bind(this); } Navbar.prototype.getChildContext = function getChildContext() { var _props = this.props; var bsClass = _props.bsClass; var expanded = _props.expanded; return { $bs_navbar: { bsClass: bsClass, expanded: expanded, onToggle: this.handleToggle } }; }; Navbar.prototype.handleToggle = function handleToggle() { var _props2 = this.props; var onToggle = _props2.onToggle; var expanded = _props2.expanded; onToggle(!expanded); }; Navbar.prototype.render = function render() { var _extends2; var _props3 = this.props; var Component = _props3.componentClass; var fixedTop = _props3.fixedTop; var fixedBottom = _props3.fixedBottom; var staticTop = _props3.staticTop; var inverse = _props3.inverse; var fluid = _props3.fluid; var className = _props3.className; var children = _props3.children; var props = _objectWithoutProperties(_props3, ['componentClass', 'fixedTop', 'fixedBottom', 'staticTop', 'inverse', 'fluid', 'className', 'children']); var _splitBsPropsAndOmit = _utilsBootstrapUtils.splitBsPropsAndOmit(props, ['expanded', 'onToggle']); var bsProps = _splitBsPropsAndOmit[0]; var elementProps = _splitBsPropsAndOmit[1]; // will result in some false positives but that seems better // than false negatives. strict `undefined` check allows explicit // "nulling" of the role if the user really doesn't want one if (elementProps.role === undefined && Component !== 'nav') { elementProps.role = 'navigation'; } if (inverse) { bsProps.bsStyle = _utilsStyleConfig.Style.INVERSE; } var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'fixed-top')] = fixedTop, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'fixed-bottom')] = fixedBottom, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'static-top')] = staticTop, _extends2)); return _react2['default'].createElement( Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), _react2['default'].createElement( _Grid2['default'], { fluid: fluid }, children ) ); }; return Navbar; })(_react2['default'].Component); Navbar.propTypes = propTypes; Navbar.defaultProps = defaultProps; Navbar.childContextTypes = childContextTypes; _utilsBootstrapUtils.bsClass('navbar', Navbar); var UncontrollableNavbar = _uncontrollable2['default'](Navbar, { expanded: 'onToggle' }); function createSimpleWrapper(tag, suffix, displayName) { var Wrapper = function Wrapper(_ref, _ref2) { var Component = _ref.componentClass; var className = _ref.className; var pullRight = _ref.pullRight; var pullLeft = _ref.pullLeft; var props = _objectWithoutProperties(_ref, ['componentClass', 'className', 'pullRight', 'pullLeft']); var _ref2$$bs_navbar = _ref2.$bs_navbar; var navbarProps = _ref2$$bs_navbar === undefined ? { bsClass: 'navbar' } : _ref2$$bs_navbar; return _react2['default'].createElement(Component, _extends({}, props, { className: _classnames2['default'](className, _utilsBootstrapUtils.prefix(navbarProps, suffix), pullRight && _utilsBootstrapUtils.prefix(navbarProps, 'right'), pullLeft && _utilsBootstrapUtils.prefix(navbarProps, 'left')) })); }; Wrapper.displayName = displayName; Wrapper.propTypes = { componentClass: _reactPropTypesLibElementType2['default'], pullRight: _react2['default'].PropTypes.bool, pullLeft: _react2['default'].PropTypes.bool }; Wrapper.defaultProps = { componentClass: tag, pullRight: false, pullLeft: false }; Wrapper.contextTypes = { $bs_navbar: _react.PropTypes.shape({ bsClass: _react.PropTypes.string }) }; return Wrapper; } UncontrollableNavbar.Brand = _NavbarBrand2['default']; UncontrollableNavbar.Header = _NavbarHeader2['default']; UncontrollableNavbar.Toggle = _NavbarToggle2['default']; UncontrollableNavbar.Collapse = _NavbarCollapse2['default']; UncontrollableNavbar.Form = createSimpleWrapper('div', 'form', 'NavbarForm'); UncontrollableNavbar.Text = createSimpleWrapper('p', 'text', 'NavbarText'); UncontrollableNavbar.Link = createSimpleWrapper('a', 'link', 'NavbarLink'); // Set bsStyles here so they can be overridden. exports['default'] = _utilsBootstrapUtils.bsStyles([_utilsStyleConfig.Style.DEFAULT, _utilsStyleConfig.Style.INVERSE], _utilsStyleConfig.Style.DEFAULT, UncontrollableNavbar); module.exports = exports['default']; /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var contextTypes = { $bs_navbar: _react2['default'].PropTypes.shape({ bsClass: _react2['default'].PropTypes.string }) }; var NavbarBrand = (function (_React$Component) { _inherits(NavbarBrand, _React$Component); function NavbarBrand() { _classCallCheck(this, NavbarBrand); _React$Component.apply(this, arguments); } NavbarBrand.prototype.render = function render() { var _props = this.props; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['className', 'children']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = _utilsBootstrapUtils.prefix(navbarProps, 'brand'); if (_react2['default'].isValidElement(children)) { return _react2['default'].cloneElement(children, { className: _classnames2['default'](children.props.className, className, bsClassName) }); } return _react2['default'].createElement( 'span', _extends({}, props, { className: _classnames2['default'](className, bsClassName) }), children ); }; return NavbarBrand; })(_react2['default'].Component); NavbarBrand.contextTypes = contextTypes; exports['default'] = NavbarBrand; module.exports = exports['default']; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Collapse = __webpack_require__(70); var _Collapse2 = _interopRequireDefault(_Collapse); var _utilsBootstrapUtils = __webpack_require__(34); var contextTypes = { $bs_navbar: _react.PropTypes.shape({ bsClass: _react.PropTypes.string, expanded: _react.PropTypes.bool }) }; var NavbarCollapse = (function (_React$Component) { _inherits(NavbarCollapse, _React$Component); function NavbarCollapse() { _classCallCheck(this, NavbarCollapse); _React$Component.apply(this, arguments); } NavbarCollapse.prototype.render = function render() { var _props = this.props; var children = _props.children; var props = _objectWithoutProperties(_props, ['children']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = _utilsBootstrapUtils.prefix(navbarProps, 'collapse'); return _react2['default'].createElement( _Collapse2['default'], _extends({ 'in': navbarProps.expanded }, props), _react2['default'].createElement( 'div', { className: bsClassName }, children ) ); }; return NavbarCollapse; })(_react2['default'].Component); NavbarCollapse.contextTypes = contextTypes; exports['default'] = NavbarCollapse; module.exports = exports['default']; /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var contextTypes = { $bs_navbar: _react2['default'].PropTypes.shape({ bsClass: _react2['default'].PropTypes.string }) }; var NavbarHeader = (function (_React$Component) { _inherits(NavbarHeader, _React$Component); function NavbarHeader() { _classCallCheck(this, NavbarHeader); _React$Component.apply(this, arguments); } NavbarHeader.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = _utilsBootstrapUtils.prefix(navbarProps, 'header'); return _react2['default'].createElement('div', _extends({}, props, { className: _classnames2['default'](className, bsClassName) })); }; return NavbarHeader; })(_react2['default'].Component); NavbarHeader.contextTypes = contextTypes; exports['default'] = NavbarHeader; module.exports = exports['default']; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var propTypes = { onClick: _react.PropTypes.func, /** * The toggle content, if left empty it will render the default toggle (seen above). */ children: _react.PropTypes.node }; var contextTypes = { $bs_navbar: _react.PropTypes.shape({ bsClass: _react.PropTypes.string, expanded: _react.PropTypes.bool, onToggle: _react.PropTypes.func.isRequired }) }; var NavbarToggle = (function (_React$Component) { _inherits(NavbarToggle, _React$Component); function NavbarToggle() { _classCallCheck(this, NavbarToggle); _React$Component.apply(this, arguments); } NavbarToggle.prototype.render = function render() { var _props = this.props; var onClick = _props.onClick; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['onClick', 'className', 'children']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var buttonProps = _extends({ type: 'button' }, props, { onClick: _utilsCreateChainedFunction2['default'](onClick, navbarProps.onToggle), className: _classnames2['default'](className, _utilsBootstrapUtils.prefix(navbarProps, 'toggle'), !navbarProps.expanded && 'collapsed') }); if (children) { return _react2['default'].createElement( 'button', buttonProps, children ); } return _react2['default'].createElement( 'button', buttonProps, _react2['default'].createElement( 'span', { className: 'sr-only' }, 'Toggle navigation' ), _react2['default'].createElement('span', { className: 'icon-bar' }), _react2['default'].createElement('span', { className: 'icon-bar' }), _react2['default'].createElement('span', { className: 'icon-bar' }) ); }; return NavbarToggle; })(_react2['default'].Component); NavbarToggle.propTypes = propTypes; NavbarToggle.contextTypes = contextTypes; exports['default'] = NavbarToggle; module.exports = exports['default']; /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(20)['default']; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Dropdown = __webpack_require__(83); var _Dropdown2 = _interopRequireDefault(_Dropdown); var _utilsSplitComponentProps = __webpack_require__(126); var _utilsSplitComponentProps2 = _interopRequireDefault(_utilsSplitComponentProps); var propTypes = _extends({}, _Dropdown2['default'].propTypes, { // Toggle props. title: _react2['default'].PropTypes.node.isRequired, noCaret: _react2['default'].PropTypes.bool, active: _react2['default'].PropTypes.bool, // Override generated docs from <Dropdown>. /** * @private */ children: _react2['default'].PropTypes.node }); var NavDropdown = (function (_React$Component) { _inherits(NavDropdown, _React$Component); function NavDropdown() { _classCallCheck(this, NavDropdown); _React$Component.apply(this, arguments); } NavDropdown.prototype.render = function render() { var _props = this.props; var title = _props.title; var active = _props.active; var className = _props.className; var style = _props.style; var children = _props.children; var props = _objectWithoutProperties(_props, ['title', 'active', 'className', 'style', 'children']); delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; var _splitComponentProps = _utilsSplitComponentProps2['default'](props, _Dropdown2['default'].ControlledComponent); var dropdownProps = _splitComponentProps[0]; var toggleProps = _splitComponentProps[1]; // Unlike for the other dropdowns, styling needs to go to the `<Dropdown>` // rather than the `<Dropdown.Toggle>`. return _react2['default'].createElement( _Dropdown2['default'], _extends({}, dropdownProps, { componentClass: 'li', className: _classnames2['default'](className, { active: active }), style: style }), _react2['default'].createElement( _Dropdown2['default'].Toggle, _extends({}, toggleProps, { useAnchor: true }), title ), _react2['default'].createElement( _Dropdown2['default'].Menu, null, children ) ); }; return NavDropdown; })(_react2['default'].Component); NavDropdown.propTypes = propTypes; exports['default'] = NavDropdown; module.exports = exports['default']; /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _SafeAnchor = __webpack_require__(51); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var propTypes = { active: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, role: _react2['default'].PropTypes.string, href: _react2['default'].PropTypes.string, onClick: _react2['default'].PropTypes.func, onSelect: _react2['default'].PropTypes.func, eventKey: _react2['default'].PropTypes.any }; var defaultProps = { active: false, disabled: false }; var NavItem = (function (_React$Component) { _inherits(NavItem, _React$Component); function NavItem(props, context) { _classCallCheck(this, NavItem); _React$Component.call(this, props, context); this.handleClick = this.handleClick.bind(this); } NavItem.prototype.handleClick = function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } }; NavItem.prototype.render = function render() { var _props = this.props; var active = _props.active; var disabled = _props.disabled; var onClick = _props.onClick; var className = _props.className; var style = _props.style; var props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; if (!props.role) { if (props.href === '#') { props.role = 'button'; } } else if (props.role === 'tab') { props['aria-selected'] = active; } return _react2['default'].createElement( 'li', { role: 'presentation', className: _classnames2['default'](className, { active: active, disabled: disabled }), style: style }, _react2['default'].createElement(_SafeAnchor2['default'], _extends({}, props, { disabled: disabled, onClick: _utilsCreateChainedFunction2['default'](onClick, this.handleClick) })) ); }; return NavItem; })(_react2['default'].Component); NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; exports['default'] = NavItem; module.exports = exports['default']; /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(20)['default']; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactOverlaysLibOverlay = __webpack_require__(183); var _reactOverlaysLibOverlay2 = _interopRequireDefault(_reactOverlaysLibOverlay); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _Fade = __webpack_require__(127); var _Fade2 = _interopRequireDefault(_Fade); var propTypes = _extends({}, _reactOverlaysLibOverlay2['default'].propTypes, { /** * Set the visibility of the Overlay */ show: _react2['default'].PropTypes.bool, /** * Specify whether the overlay should trigger onHide when the user clicks outside the overlay */ rootClose: _react2['default'].PropTypes.bool, /** * A callback invoked by the overlay when it wishes to be hidden. Required if * `rootClose` is specified. */ onHide: _react2['default'].PropTypes.func, /** * Use animation */ animation: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.bool, _reactPropTypesLibElementType2['default']]), /** * Callback fired before the Overlay transitions in */ onEnter: _react2['default'].PropTypes.func, /** * Callback fired as the Overlay begins to transition in */ onEntering: _react2['default'].PropTypes.func, /** * Callback fired after the Overlay finishes transitioning in */ onEntered: _react2['default'].PropTypes.func, /** * Callback fired right before the Overlay transitions out */ onExit: _react2['default'].PropTypes.func, /** * Callback fired as the Overlay begins to transition out */ onExiting: _react2['default'].PropTypes.func, /** * Callback fired after the Overlay finishes transitioning out */ onExited: _react2['default'].PropTypes.func }); var defaultProps = { animation: _Fade2['default'], rootClose: false, show: false }; var Overlay = (function (_React$Component) { _inherits(Overlay, _React$Component); function Overlay() { _classCallCheck(this, Overlay); _React$Component.apply(this, arguments); } Overlay.prototype.render = function render() { var _props = this.props; var animation = _props.animation; var children = _props.children; var props = _objectWithoutProperties(_props, ['animation', 'children']); var transition = animation === true ? _Fade2['default'] : animation || null; var child = undefined; if (!transition) { child = _react.cloneElement(children, { className: _classnames2['default'](children.props.className, 'in') }); } else { child = children; } return _react2['default'].createElement( _reactOverlaysLibOverlay2['default'], _extends({}, props, { transition: transition }), child ); }; return Overlay; })(_react2['default'].Component); Overlay.propTypes = propTypes; Overlay.defaultProps = defaultProps; exports['default'] = Overlay; module.exports = exports['default']; /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Portal = __webpack_require__(158); var _Portal2 = _interopRequireDefault(_Portal); var _Position = __webpack_require__(184); var _Position2 = _interopRequireDefault(_Position); var _RootCloseWrapper = __webpack_require__(118); var _RootCloseWrapper2 = _interopRequireDefault(_RootCloseWrapper); var _elementType = __webpack_require__(52); var _elementType2 = _interopRequireDefault(_elementType); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Built on top of `<Position/>` and `<Portal/>`, the overlay component is great for custom tooltip overlays. */ var Overlay = function (_React$Component) { _inherits(Overlay, _React$Component); function Overlay(props, context) { _classCallCheck(this, Overlay); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Overlay).call(this, props, context)); _this.state = { exited: !props.show }; _this.onHiddenListener = _this.handleHidden.bind(_this); return _this; } _createClass(Overlay, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.show) { this.setState({ exited: false }); } else if (!nextProps.transition) { // Otherwise let handleHidden take care of marking exited. this.setState({ exited: true }); } } }, { key: 'render', value: function render() { var _props = this.props; var container = _props.container; var containerPadding = _props.containerPadding; var target = _props.target; var placement = _props.placement; var shouldUpdatePosition = _props.shouldUpdatePosition; var rootClose = _props.rootClose; var children = _props.children; var Transition = _props.transition; var props = _objectWithoutProperties(_props, ['container', 'containerPadding', 'target', 'placement', 'shouldUpdatePosition', 'rootClose', 'children', 'transition']); // Don't un-render the overlay while it's transitioning out. var mountOverlay = props.show || Transition && !this.state.exited; if (!mountOverlay) { // Don't bother showing anything if we don't have to. return null; } var child = children; // Position is be inner-most because it adds inline styles into the child, // which the other wrappers don't forward correctly. child = _react2.default.createElement( _Position2.default, { container: container, containerPadding: containerPadding, target: target, placement: placement, shouldUpdatePosition: shouldUpdatePosition }, child ); if (Transition) { var onExit = props.onExit; var onExiting = props.onExiting; var onEnter = props.onEnter; var onEntering = props.onEntering; var onEntered = props.onEntered; // This animates the child node by injecting props, so it must precede // anything that adds a wrapping div. child = _react2.default.createElement( Transition, { 'in': props.show, transitionAppear: true, onExit: onExit, onExiting: onExiting, onExited: this.onHiddenListener, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered }, child ); } // This goes after everything else because it adds a wrapping div. if (rootClose) { child = _react2.default.createElement( _RootCloseWrapper2.default, { onRootClose: props.onHide }, child ); } return _react2.default.createElement( _Portal2.default, { container: container }, child ); } }, { key: 'handleHidden', value: function handleHidden() { this.setState({ exited: true }); if (this.props.onExited) { var _props2; (_props2 = this.props).onExited.apply(_props2, arguments); } } }]); return Overlay; }(_react2.default.Component); Overlay.propTypes = _extends({}, _Portal2.default.propTypes, _Position2.default.propTypes, { /** * Set the visibility of the Overlay */ show: _react2.default.PropTypes.bool, /** * Specify whether the overlay should trigger `onHide` when the user clicks outside the overlay */ rootClose: _react2.default.PropTypes.bool, /** * A Callback fired by the Overlay when it wishes to be hidden. * * __required__ when `rootClose` is `true`. * * @type func */ onHide: function onHide(props, name, cname) { var pt = _react2.default.PropTypes.func; if (props.rootClose) pt = pt.isRequired; return pt(props, name, cname); }, /** * A `<Transition/>` component used to animate the overlay changes visibility. */ transition: _elementType2.default, /** * Callback fired before the Overlay transitions in */ onEnter: _react2.default.PropTypes.func, /** * Callback fired as the Overlay begins to transition in */ onEntering: _react2.default.PropTypes.func, /** * Callback fired after the Overlay finishes transitioning in */ onEntered: _react2.default.PropTypes.func, /** * Callback fired right before the Overlay transitions out */ onExit: _react2.default.PropTypes.func, /** * Callback fired as the Overlay begins to transition out */ onExiting: _react2.default.PropTypes.func, /** * Callback fired after the Overlay finishes transitioning out */ onExited: _react2.default.PropTypes.func }); exports.default = Overlay; module.exports = exports['default']; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _mountable = __webpack_require__(157); var _mountable2 = _interopRequireDefault(_mountable); var _calculatePosition = __webpack_require__(185); var _calculatePosition2 = _interopRequireDefault(_calculatePosition); var _getContainer = __webpack_require__(159); var _getContainer2 = _interopRequireDefault(_getContainer); var _ownerDocument = __webpack_require__(122); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * The Position component calculates the coordinates for its child, to position * it relative to a `target` component or node. Useful for creating callouts * and tooltips, the Position component injects a `style` props with `left` and * `top` values for positioning your component. * * It also injects "arrow" `left`, and `top` values for styling callout arrows * for giving your components a sense of directionality. */ var Position = function (_React$Component) { _inherits(Position, _React$Component); function Position(props, context) { _classCallCheck(this, Position); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Position).call(this, props, context)); _this.state = { positionLeft: 0, positionTop: 0, arrowOffsetLeft: null, arrowOffsetTop: null }; _this._needsFlush = false; _this._lastTarget = null; return _this; } _createClass(Position, [{ key: 'componentDidMount', value: function componentDidMount() { this.updatePosition(this.getTarget()); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps() { this._needsFlush = true; } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { if (this._needsFlush) { this._needsFlush = false; this.maybeUpdatePosition(this.props.placement !== prevProps.placement); } } }, { key: 'render', value: function render() { var _props = this.props; var children = _props.children; var className = _props.className; var props = _objectWithoutProperties(_props, ['children', 'className']); var _state = this.state; var positionLeft = _state.positionLeft; var positionTop = _state.positionTop; var arrowPosition = _objectWithoutProperties(_state, ['positionLeft', 'positionTop']); // These should not be forwarded to the child. delete props.target; delete props.container; delete props.containerPadding; delete props.shouldUpdatePosition; var child = _react2.default.Children.only(children); return (0, _react.cloneElement)(child, _extends({}, props, arrowPosition, { // FIXME: Don't forward `positionLeft` and `positionTop` via both props // and `props.style`. positionLeft: positionLeft, positionTop: positionTop, className: (0, _classnames2.default)(className, child.props.className), style: _extends({}, child.props.style, { left: positionLeft, top: positionTop }) })); } }, { key: 'getTarget', value: function getTarget() { var target = this.props.target; var targetElement = typeof target === 'function' ? target() : target; return targetElement && _reactDom2.default.findDOMNode(targetElement) || null; } }, { key: 'maybeUpdatePosition', value: function maybeUpdatePosition(placementChanged) { var target = this.getTarget(); if (!this.props.shouldUpdatePosition && target === this._lastTarget && !placementChanged) { return; } this.updatePosition(target); } }, { key: 'updatePosition', value: function updatePosition(target) { this._lastTarget = target; if (!target) { this.setState({ positionLeft: 0, positionTop: 0, arrowOffsetLeft: null, arrowOffsetTop: null }); return; } var overlay = _reactDom2.default.findDOMNode(this); var container = (0, _getContainer2.default)(this.props.container, (0, _ownerDocument2.default)(this).body); this.setState((0, _calculatePosition2.default)(this.props.placement, overlay, target, container, this.props.containerPadding)); } }]); return Position; }(_react2.default.Component); Position.propTypes = { /** * A node, element, or function that returns either. The child will be * be positioned next to the `target` specified. */ target: _react2.default.PropTypes.oneOfType([_mountable2.default, _react2.default.PropTypes.func]), /** * "offsetParent" of the component */ container: _react2.default.PropTypes.oneOfType([_mountable2.default, _react2.default.PropTypes.func]), /** * Minimum spacing in pixels between container border and component border */ containerPadding: _react2.default.PropTypes.number, /** * How to position the component relative to the target */ placement: _react2.default.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * Whether the position should be changed on each update */ shouldUpdatePosition: _react2.default.PropTypes.bool }; Position.displayName = 'Position'; Position.defaultProps = { containerPadding: 0, placement: 'right', shouldUpdatePosition: false }; exports.default = Position; module.exports = exports['default']; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = calculatePosition; var _offset = __webpack_require__(186); var _offset2 = _interopRequireDefault(_offset); var _position = __webpack_require__(187); var _position2 = _interopRequireDefault(_position); var _scrollTop = __webpack_require__(189); var _scrollTop2 = _interopRequireDefault(_scrollTop); var _ownerDocument = __webpack_require__(122); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getContainerDimensions(containerNode) { var width = void 0, height = void 0, scroll = void 0; if (containerNode.tagName === 'BODY') { width = window.innerWidth; height = window.innerHeight; scroll = (0, _scrollTop2.default)((0, _ownerDocument2.default)(containerNode).documentElement) || (0, _scrollTop2.default)(containerNode); } else { var _getOffset = (0, _offset2.default)(containerNode); width = _getOffset.width; height = _getOffset.height; scroll = (0, _scrollTop2.default)(containerNode); } return { width: width, height: height, scroll: scroll }; } function getTopDelta(top, overlayHeight, container, padding) { var containerDimensions = getContainerDimensions(container); var containerScroll = containerDimensions.scroll; var containerHeight = containerDimensions.height; var topEdgeOffset = top - padding - containerScroll; var bottomEdgeOffset = top + padding - containerScroll + overlayHeight; if (topEdgeOffset < 0) { return -topEdgeOffset; } else if (bottomEdgeOffset > containerHeight) { return containerHeight - bottomEdgeOffset; } else { return 0; } } function getLeftDelta(left, overlayWidth, container, padding) { var containerDimensions = getContainerDimensions(container); var containerWidth = containerDimensions.width; var leftEdgeOffset = left - padding; var rightEdgeOffset = left + padding + overlayWidth; if (leftEdgeOffset < 0) { return -leftEdgeOffset; } else if (rightEdgeOffset > containerWidth) { return containerWidth - rightEdgeOffset; } return 0; } function calculatePosition(placement, overlayNode, target, container, padding) { var childOffset = container.tagName === 'BODY' ? (0, _offset2.default)(target) : (0, _position2.default)(target, container); var _getOffset2 = (0, _offset2.default)(overlayNode); var overlayHeight = _getOffset2.height; var overlayWidth = _getOffset2.width; var positionLeft = void 0, positionTop = void 0, arrowOffsetLeft = void 0, arrowOffsetTop = void 0; if (placement === 'left' || placement === 'right') { positionTop = childOffset.top + (childOffset.height - overlayHeight) / 2; if (placement === 'left') { positionLeft = childOffset.left - overlayWidth; } else { positionLeft = childOffset.left + childOffset.width; } var topDelta = getTopDelta(positionTop, overlayHeight, container, padding); positionTop += topDelta; arrowOffsetTop = 50 * (1 - 2 * topDelta / overlayHeight) + '%'; arrowOffsetLeft = void 0; } else if (placement === 'top' || placement === 'bottom') { positionLeft = childOffset.left + (childOffset.width - overlayWidth) / 2; if (placement === 'top') { positionTop = childOffset.top - overlayHeight; } else { positionTop = childOffset.top + childOffset.height; } var leftDelta = getLeftDelta(positionLeft, overlayWidth, container, padding); positionLeft += leftDelta; arrowOffsetLeft = 50 * (1 - 2 * leftDelta / overlayWidth) + '%'; arrowOffsetTop = void 0; } else { throw new Error('calcOverlayPosition(): No such placement of "' + placement + '" found.'); } return { positionLeft: positionLeft, positionTop: positionTop, arrowOffsetLeft: arrowOffsetLeft, arrowOffsetTop: arrowOffsetTop }; } module.exports = exports['default']; /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var contains = __webpack_require__(86), getWindow = __webpack_require__(166), ownerDocument = __webpack_require__(85); module.exports = function offset(node) { var doc = ownerDocument(node), win = getWindow(doc), docElem = doc && doc.documentElement, box = { top: 0, left: 0, height: 0, width: 0 }; if (!doc) return; // Make sure it's not a disconnected DOM node if (!contains(docElem, node)) return box; if (node.getBoundingClientRect !== undefined) box = node.getBoundingClientRect(); if (box.width || box.height) { box = { top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0), width: (box.width == null ? node.offsetWidth : box.width) || 0, height: (box.height == null ? node.offsetHeight : box.height) || 0 }; } return box; }; /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(77); exports.__esModule = true; exports['default'] = position; var _offset = __webpack_require__(186); var _offset2 = babelHelpers.interopRequireDefault(_offset); var _offsetParent = __webpack_require__(188); var _offsetParent2 = babelHelpers.interopRequireDefault(_offsetParent); var _scrollTop = __webpack_require__(189); var _scrollTop2 = babelHelpers.interopRequireDefault(_scrollTop); var _scrollLeft = __webpack_require__(190); var _scrollLeft2 = babelHelpers.interopRequireDefault(_scrollLeft); var _style = __webpack_require__(71); var _style2 = babelHelpers.interopRequireDefault(_style); function nodeName(node) { return node.nodeName && node.nodeName.toLowerCase(); } function position(node, offsetParent) { var parentOffset = { top: 0, left: 0 }, offset; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, // because it is its only offset parent if ((0, _style2['default'])(node, 'position') === 'fixed') { offset = node.getBoundingClientRect(); } else { offsetParent = offsetParent || (0, _offsetParent2['default'])(node); offset = (0, _offset2['default'])(node); if (nodeName(offsetParent) !== 'html') parentOffset = (0, _offset2['default'])(offsetParent); parentOffset.top += parseInt((0, _style2['default'])(offsetParent, 'borderTopWidth'), 10) - (0, _scrollTop2['default'])(offsetParent) || 0; parentOffset.left += parseInt((0, _style2['default'])(offsetParent, 'borderLeftWidth'), 10) - (0, _scrollLeft2['default'])(offsetParent) || 0; } // Subtract parent offsets and node margins return babelHelpers._extends({}, offset, { top: offset.top - parentOffset.top - (parseInt((0, _style2['default'])(node, 'marginTop'), 10) || 0), left: offset.left - parentOffset.left - (parseInt((0, _style2['default'])(node, 'marginLeft'), 10) || 0) }); } module.exports = exports['default']; /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(77); exports.__esModule = true; exports['default'] = offsetParent; var _ownerDocument = __webpack_require__(85); var _ownerDocument2 = babelHelpers.interopRequireDefault(_ownerDocument); var _style = __webpack_require__(71); var _style2 = babelHelpers.interopRequireDefault(_style); function nodeName(node) { return node.nodeName && node.nodeName.toLowerCase(); } function offsetParent(node) { var doc = (0, _ownerDocument2['default'])(node), offsetParent = node && node.offsetParent; while (offsetParent && nodeName(node) !== 'html' && (0, _style2['default'])(offsetParent, 'position') === 'static') { offsetParent = offsetParent.offsetParent; } return offsetParent || doc.documentElement; } module.exports = exports['default']; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var getWindow = __webpack_require__(166); module.exports = function scrollTop(node, val) { var win = getWindow(node); if (val === undefined) return win ? 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop : node.scrollTop; if (win) win.scrollTo('pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft, val);else node.scrollTop = val; }; /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var getWindow = __webpack_require__(166); module.exports = function scrollTop(node, val) { var win = getWindow(node); if (val === undefined) return win ? 'pageXOffset' in win ? win.pageXOffset : win.document.documentElement.scrollLeft : node.scrollLeft; if (win) win.scrollTo(val, 'pageYOffset' in win ? win.pageYOffset : win.document.documentElement.scrollTop);else node.scrollLeft = val; }; /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(20)['default']; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _domHelpersQueryContains = __webpack_require__(86); var _domHelpersQueryContains2 = _interopRequireDefault(_domHelpersQueryContains); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(61); var _reactDom2 = _interopRequireDefault(_reactDom); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _Overlay = __webpack_require__(182); var _Overlay2 = _interopRequireDefault(_Overlay); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); /** * Check if value one is inside or equal to the of value * * @param {string} one * @param {string|array} of * @returns {boolean} */ function isOneOf(one, of) { if (Array.isArray(of)) { return of.indexOf(one) >= 0; } return one === of; } var triggerType = _react2['default'].PropTypes.oneOf(['click', 'hover', 'focus']); var propTypes = _extends({}, _Overlay2['default'].propTypes, { /** * Specify which action or actions trigger Overlay visibility */ trigger: _react2['default'].PropTypes.oneOfType([triggerType, _react2['default'].PropTypes.arrayOf(triggerType)]), /** * A millisecond delay amount to show and hide the Overlay once triggered */ delay: _react2['default'].PropTypes.number, /** * A millisecond delay amount before showing the Overlay once triggered. */ delayShow: _react2['default'].PropTypes.number, /** * A millisecond delay amount before hiding the Overlay once triggered. */ delayHide: _react2['default'].PropTypes.number, // FIXME: This should be `defaultShow`. /** * The initial visibility state of the Overlay. For more nuanced visibility * control, consider using the Overlay component directly. */ defaultOverlayShown: _react2['default'].PropTypes.bool, /** * An element or text to overlay next to the target. */ overlay: _react2['default'].PropTypes.node.isRequired, /** * @private */ onBlur: _react2['default'].PropTypes.func, /** * @private */ onClick: _react2['default'].PropTypes.func, /** * @private */ onFocus: _react2['default'].PropTypes.func, /** * @private */ onMouseOut: _react2['default'].PropTypes.func, /** * @private */ onMouseOver: _react2['default'].PropTypes.func, // Overridden props from `<Overlay>`. /** * @private */ target: _react2['default'].PropTypes.oneOf([null]), /** * @private */ onHide: _react2['default'].PropTypes.oneOf([null]), /** * @private */ show: _react2['default'].PropTypes.oneOf([null]) }); var defaultProps = { defaultOverlayShown: false, trigger: ['hover', 'focus'] }; var OverlayTrigger = (function (_React$Component) { _inherits(OverlayTrigger, _React$Component); function OverlayTrigger(props, context) { var _this = this; _classCallCheck(this, OverlayTrigger); _React$Component.call(this, props, context); this.handleToggle = this.handleToggle.bind(this); this.handleDelayedShow = this.handleDelayedShow.bind(this); this.handleDelayedHide = this.handleDelayedHide.bind(this); this.handleMouseOver = function (e) { return _this.handleMouseOverOut(_this.handleDelayedShow, e); }; this.handleMouseOut = function (e) { return _this.handleMouseOverOut(_this.handleDelayedHide, e); }; this._mountNode = null; this.state = { show: props.defaultOverlayShown }; } OverlayTrigger.prototype.componentDidMount = function componentDidMount() { this._mountNode = document.createElement('div'); this.renderOverlay(); }; OverlayTrigger.prototype.componentDidUpdate = function componentDidUpdate() { this.renderOverlay(); }; OverlayTrigger.prototype.componentWillUnmount = function componentWillUnmount() { _reactDom2['default'].unmountComponentAtNode(this._mountNode); this._mountNode = null; clearTimeout(this._hoverShowDelay); clearTimeout(this._hoverHideDelay); }; OverlayTrigger.prototype.handleToggle = function handleToggle() { if (this.state.show) { this.hide(); } else { this.show(); } }; OverlayTrigger.prototype.handleDelayedShow = function handleDelayedShow() { var _this2 = this; if (this._hoverHideDelay != null) { clearTimeout(this._hoverHideDelay); this._hoverHideDelay = null; return; } if (this.state.show || this._hoverShowDelay != null) { return; } var delay = this.props.delayShow != null ? this.props.delayShow : this.props.delay; if (!delay) { this.show(); return; } this._hoverShowDelay = setTimeout(function () { _this2._hoverShowDelay = null; _this2.show(); }, delay); }; OverlayTrigger.prototype.handleDelayedHide = function handleDelayedHide() { var _this3 = this; if (this._hoverShowDelay != null) { clearTimeout(this._hoverShowDelay); this._hoverShowDelay = null; return; } if (!this.state.show || this._hoverHideDelay != null) { return; } var delay = this.props.delayHide != null ? this.props.delayHide : this.props.delay; if (!delay) { this.hide(); return; } this._hoverHideDelay = setTimeout(function () { _this3._hoverHideDelay = null; _this3.hide(); }, delay); }; // Simple implementation of mouseEnter and mouseLeave. // React's built version is broken: https://github.com/facebook/react/issues/4251 // for cases when the trigger is disabled and mouseOut/Over can cause flicker // moving from one child element to another. OverlayTrigger.prototype.handleMouseOverOut = function handleMouseOverOut(handler, e) { var target = e.currentTarget; var related = e.relatedTarget || e.nativeEvent.toElement; if (!related || related !== target && !_domHelpersQueryContains2['default'](target, related)) { handler(e); } }; OverlayTrigger.prototype.show = function show() { this.setState({ show: true }); }; OverlayTrigger.prototype.hide = function hide() { this.setState({ show: false }); }; OverlayTrigger.prototype.makeOverlay = function makeOverlay(overlay, props) { return _react2['default'].createElement( _Overlay2['default'], _extends({}, props, { show: this.state.show, onHide: this.handleToggle, target: this }), overlay ); }; OverlayTrigger.prototype.renderOverlay = function renderOverlay() { _reactDom2['default'].unstable_renderSubtreeIntoContainer(this, this._overlay, this._mountNode); }; OverlayTrigger.prototype.render = function render() { var _props = this.props; var trigger = _props.trigger; var overlay = _props.overlay; var children = _props.children; var onBlur = _props.onBlur; var onClick = _props.onClick; var onFocus = _props.onFocus; var onMouseOut = _props.onMouseOut; var onMouseOver = _props.onMouseOver; var props = _objectWithoutProperties(_props, ['trigger', 'overlay', 'children', 'onBlur', 'onClick', 'onFocus', 'onMouseOut', 'onMouseOver']); delete props.delay; delete props.delayShow; delete props.delayHide; delete props.defaultOverlayShown; var child = _react2['default'].Children.only(children); var childProps = child.props; var triggerProps = { 'aria-describedby': overlay.props.id }; // FIXME: The logic here for passing through handlers on this component is // inconsistent. We shouldn't be passing any of these props through. triggerProps.onClick = _utilsCreateChainedFunction2['default'](childProps.onClick, onClick); if (isOneOf('click', trigger)) { triggerProps.onClick = _utilsCreateChainedFunction2['default'](triggerProps.onClick, this.handleToggle); } if (isOneOf('hover', trigger)) { true ? _warning2['default'](!(trigger === 'hover'), '[react-bootstrap] Specifying only the `"hover"` trigger limits the ' + 'visibility of the overlay to just mouse users. Consider also ' + 'including the `"focus"` trigger so that touch and keyboard only ' + 'users can see the overlay as well.') : undefined; triggerProps.onMouseOver = _utilsCreateChainedFunction2['default'](childProps.onMouseOver, onMouseOver, this.handleMouseOver); triggerProps.onMouseOut = _utilsCreateChainedFunction2['default'](childProps.onMouseOut, onMouseOut, this.handleMouseOut); } if (isOneOf('focus', trigger)) { triggerProps.onFocus = _utilsCreateChainedFunction2['default'](childProps.onFocus, onFocus, this.handleDelayedShow); triggerProps.onBlur = _utilsCreateChainedFunction2['default'](childProps.onBlur, onBlur, this.handleDelayedHide); } this._overlay = this.makeOverlay(overlay, props); return _react.cloneElement(child, triggerProps); }; return OverlayTrigger; })(_react2['default'].Component); OverlayTrigger.propTypes = propTypes; OverlayTrigger.defaultProps = defaultProps; exports['default'] = OverlayTrigger; module.exports = exports['default']; /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var PageHeader = (function (_React$Component) { _inherits(PageHeader, _React$Component); function PageHeader() { _classCallCheck(this, PageHeader); _React$Component.apply(this, arguments); } PageHeader.prototype.render = function render() { var _props = this.props; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['className', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement( 'div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), _react2['default'].createElement( 'h1', null, children ) ); }; return PageHeader; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('page-header', PageHeader); module.exports = exports['default']; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _PagerItem = __webpack_require__(194); var _PagerItem2 = _interopRequireDefault(_PagerItem); var _utilsDeprecationWarning = __webpack_require__(195); var _utilsDeprecationWarning2 = _interopRequireDefault(_utilsDeprecationWarning); exports['default'] = _utilsDeprecationWarning2['default'].wrapper(_PagerItem2['default'], '`<PageItem>`', '`<Pager.Item>`'); module.exports = exports['default']; /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _SafeAnchor = __webpack_require__(51); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var propTypes = { disabled: _react2['default'].PropTypes.bool, previous: _react2['default'].PropTypes.bool, next: _react2['default'].PropTypes.bool, onClick: _react2['default'].PropTypes.func, onSelect: _react2['default'].PropTypes.func, eventKey: _react2['default'].PropTypes.any }; var defaultProps = { disabled: false, previous: false, next: false }; var PagerItem = (function (_React$Component) { _inherits(PagerItem, _React$Component); function PagerItem(props, context) { _classCallCheck(this, PagerItem); _React$Component.call(this, props, context); this.handleSelect = this.handleSelect.bind(this); } PagerItem.prototype.handleSelect = function handleSelect(e) { var _props = this.props; var disabled = _props.disabled; var onSelect = _props.onSelect; var eventKey = _props.eventKey; if (onSelect || disabled) { e.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, e); } }; PagerItem.prototype.render = function render() { var _props2 = this.props; var disabled = _props2.disabled; var previous = _props2.previous; var next = _props2.next; var onClick = _props2.onClick; var className = _props2.className; var style = _props2.style; var props = _objectWithoutProperties(_props2, ['disabled', 'previous', 'next', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; return _react2['default'].createElement( 'li', { className: _classnames2['default'](className, { disabled: disabled, previous: previous, next: next }), style: style }, _react2['default'].createElement(_SafeAnchor2['default'], _extends({}, props, { disabled: disabled, onClick: _utilsCreateChainedFunction2['default'](onClick, this.handleSelect) })) ); }; return PagerItem; })(_react2['default'].Component); PagerItem.propTypes = propTypes; PagerItem.defaultProps = defaultProps; exports['default'] = PagerItem; module.exports = exports['default']; /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports._resetWarned = _resetWarned; var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var warned = {}; function deprecationWarning(oldname, newname, link) { var message = undefined; if (typeof oldname === 'object') { message = oldname.message; } else { message = oldname + ' is deprecated. Use ' + newname + ' instead.'; if (link) { message += '\nYou can read more about it at ' + link; } } if (warned[message]) { return; } true ? _warning2['default'](false, message) : undefined; warned[message] = true; } deprecationWarning.wrapper = function (Component) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return (function (_Component) { _inherits(DeprecatedComponent, _Component); function DeprecatedComponent() { _classCallCheck(this, DeprecatedComponent); _Component.apply(this, arguments); } DeprecatedComponent.prototype.componentWillMount = function componentWillMount() { deprecationWarning.apply(undefined, args); if (_Component.prototype.componentWillMount) { var _Component$prototype$componentWillMount; for (var _len2 = arguments.length, methodArgs = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { methodArgs[_key2] = arguments[_key2]; } (_Component$prototype$componentWillMount = _Component.prototype.componentWillMount).call.apply(_Component$prototype$componentWillMount, [this].concat(methodArgs)); } }; return DeprecatedComponent; })(Component); }; exports['default'] = deprecationWarning; function _resetWarned() { warned = {}; } /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _PagerItem = __webpack_require__(194); var _PagerItem2 = _interopRequireDefault(_PagerItem); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var propTypes = { onSelect: _react2['default'].PropTypes.func }; var Pager = (function (_React$Component) { _inherits(Pager, _React$Component); function Pager() { _classCallCheck(this, Pager); _React$Component.apply(this, arguments); } Pager.prototype.render = function render() { var _props = this.props; var onSelect = _props.onSelect; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['onSelect', 'className', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement( 'ul', _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), _utilsValidComponentChildren2['default'].map(children, function (child) { return _react.cloneElement(child, { onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, onSelect) }); }) ); }; return Pager; })(_react2['default'].Component); Pager.propTypes = propTypes; Pager.Item = _PagerItem2['default']; exports['default'] = _utilsBootstrapUtils.bsClass('pager', Pager); module.exports = exports['default']; /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _PaginationButton = __webpack_require__(198); var _PaginationButton2 = _interopRequireDefault(_PaginationButton); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { activePage: _react2['default'].PropTypes.number, items: _react2['default'].PropTypes.number, maxButtons: _react2['default'].PropTypes.number, /** * When `true`, will display the first and the last button page */ boundaryLinks: _react2['default'].PropTypes.bool, /** * When `true`, will display the default node value ('&hellip;'). * Otherwise, will display provided node (when specified). */ ellipsis: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.bool, _react2['default'].PropTypes.node]), /** * When `true`, will display the default node value ('&laquo;'). * Otherwise, will display provided node (when specified). */ first: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.bool, _react2['default'].PropTypes.node]), /** * When `true`, will display the default node value ('&raquo;'). * Otherwise, will display provided node (when specified). */ last: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.bool, _react2['default'].PropTypes.node]), /** * When `true`, will display the default node value ('&lsaquo;'). * Otherwise, will display provided node (when specified). */ prev: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.bool, _react2['default'].PropTypes.node]), /** * When `true`, will display the default node value ('&rsaquo;'). * Otherwise, will display provided node (when specified). */ next: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.bool, _react2['default'].PropTypes.node]), onSelect: _react2['default'].PropTypes.func, /** * You can use a custom element for the buttons */ buttonComponentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { activePage: 1, items: 1, maxButtons: 0, first: false, last: false, prev: false, next: false, ellipsis: true, boundaryLinks: false }; var Pagination = (function (_React$Component) { _inherits(Pagination, _React$Component); function Pagination() { _classCallCheck(this, Pagination); _React$Component.apply(this, arguments); } Pagination.prototype.renderPageButtons = function renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps) { var pageButtons = []; var startPage = undefined; var endPage = undefined; var hasHiddenPagesAfter = undefined; if (maxButtons) { var hiddenPagesBefore = activePage - parseInt(maxButtons / 2, 10); startPage = hiddenPagesBefore > 1 ? hiddenPagesBefore : 1; hasHiddenPagesAfter = startPage + maxButtons <= items; if (!hasHiddenPagesAfter) { endPage = items; startPage = items - maxButtons + 1; if (startPage < 1) { startPage = 1; } } else { endPage = startPage + maxButtons - 1; } } else { startPage = 1; endPage = items; } for (var pagenumber = startPage; pagenumber <= endPage; pagenumber++) { pageButtons.push(_react2['default'].createElement( _PaginationButton2['default'], _extends({}, buttonProps, { key: pagenumber, eventKey: pagenumber, active: pagenumber === activePage }), pagenumber )); } if (boundaryLinks && ellipsis && startPage !== 1) { pageButtons.unshift(_react2['default'].createElement( _PaginationButton2['default'], { key: 'ellipsisFirst', disabled: true, componentClass: buttonProps.componentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'More' }, ellipsis === true ? '…' : ellipsis ) )); pageButtons.unshift(_react2['default'].createElement( _PaginationButton2['default'], _extends({}, buttonProps, { key: 1, eventKey: 1, active: false }), '1' )); } if (maxButtons && hasHiddenPagesAfter && ellipsis) { pageButtons.push(_react2['default'].createElement( _PaginationButton2['default'], { key: 'ellipsis', disabled: true, componentClass: buttonProps.componentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'More' }, ellipsis === true ? '…' : ellipsis ) )); if (boundaryLinks && endPage !== items) { pageButtons.push(_react2['default'].createElement( _PaginationButton2['default'], _extends({}, buttonProps, { key: items, eventKey: items, active: false }), items )); } } return pageButtons; }; Pagination.prototype.render = function render() { var _props = this.props; var activePage = _props.activePage; var items = _props.items; var maxButtons = _props.maxButtons; var boundaryLinks = _props.boundaryLinks; var ellipsis = _props.ellipsis; var first = _props.first; var last = _props.last; var prev = _props.prev; var next = _props.next; var onSelect = _props.onSelect; var buttonComponentClass = _props.buttonComponentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['activePage', 'items', 'maxButtons', 'boundaryLinks', 'ellipsis', 'first', 'last', 'prev', 'next', 'onSelect', 'buttonComponentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); var buttonProps = { onSelect: onSelect, componentClass: buttonComponentClass }; return _react2['default'].createElement( 'ul', _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), first && _react2['default'].createElement( _PaginationButton2['default'], _extends({}, buttonProps, { eventKey: 1, disabled: activePage === 1 }), _react2['default'].createElement( 'span', { 'aria-label': 'First' }, first === true ? '«' : first ) ), prev && _react2['default'].createElement( _PaginationButton2['default'], _extends({}, buttonProps, { eventKey: activePage - 1, disabled: activePage === 1 }), _react2['default'].createElement( 'span', { 'aria-label': 'Previous' }, prev === true ? '‹' : prev ) ), this.renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps), next && _react2['default'].createElement( _PaginationButton2['default'], _extends({}, buttonProps, { eventKey: activePage + 1, disabled: activePage >= items }), _react2['default'].createElement( 'span', { 'aria-label': 'Next' }, next === true ? '›' : next ) ), last && _react2['default'].createElement( _PaginationButton2['default'], _extends({}, buttonProps, { eventKey: items, disabled: activePage >= items }), _react2['default'].createElement( 'span', { 'aria-label': 'Last' }, last === true ? '»' : last ) ) ); }; return Pagination; })(_react2['default'].Component); Pagination.propTypes = propTypes; Pagination.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('pagination', Pagination); module.exports = exports['default']; /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _SafeAnchor = __webpack_require__(51); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); // TODO: This should be `<Pagination.Item>`. // TODO: This should use `componentClass` like other components. var propTypes = { componentClass: _reactPropTypesLibElementType2['default'], className: _react2['default'].PropTypes.string, eventKey: _react2['default'].PropTypes.any, onSelect: _react2['default'].PropTypes.func, disabled: _react2['default'].PropTypes.bool, active: _react2['default'].PropTypes.bool, onClick: _react2['default'].PropTypes.func }; var defaultProps = { componentClass: _SafeAnchor2['default'], active: false, disabled: false }; var PaginationButton = (function (_React$Component) { _inherits(PaginationButton, _React$Component); function PaginationButton(props, context) { _classCallCheck(this, PaginationButton); _React$Component.call(this, props, context); this.handleClick = this.handleClick.bind(this); } PaginationButton.prototype.handleClick = function handleClick(event) { var _props = this.props; var disabled = _props.disabled; var onSelect = _props.onSelect; var eventKey = _props.eventKey; if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; PaginationButton.prototype.render = function render() { var _props2 = this.props; var Component = _props2.componentClass; var active = _props2.active; var disabled = _props2.disabled; var onClick = _props2.onClick; var className = _props2.className; var style = _props2.style; var props = _objectWithoutProperties(_props2, ['componentClass', 'active', 'disabled', 'onClick', 'className', 'style']); if (Component === _SafeAnchor2['default']) { // Assume that custom components want `eventKey`. delete props.eventKey; } delete props.onSelect; return _react2['default'].createElement( 'li', { className: _classnames2['default'](className, { active: active, disabled: disabled }), style: style }, _react2['default'].createElement(Component, _extends({}, props, { disabled: disabled, onClick: _utilsCreateChainedFunction2['default'](onClick, this.handleClick) })) ); }; return PaginationButton; })(_react2['default'].Component); PaginationButton.propTypes = propTypes; PaginationButton.defaultProps = defaultProps; exports['default'] = PaginationButton; module.exports = exports['default']; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _Object$values = __webpack_require__(45)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Collapse = __webpack_require__(70); var _Collapse2 = _interopRequireDefault(_Collapse); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); // TODO: Use uncontrollable. var propTypes = { collapsible: _react2['default'].PropTypes.bool, onSelect: _react2['default'].PropTypes.func, header: _react2['default'].PropTypes.node, id: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]), footer: _react2['default'].PropTypes.node, defaultExpanded: _react2['default'].PropTypes.bool, expanded: _react2['default'].PropTypes.bool, eventKey: _react2['default'].PropTypes.any, headerRole: _react2['default'].PropTypes.string, panelRole: _react2['default'].PropTypes.string, // From Collapse. onEnter: _react2['default'].PropTypes.func, onEntering: _react2['default'].PropTypes.func, onEntered: _react2['default'].PropTypes.func, onExit: _react2['default'].PropTypes.func, onExiting: _react2['default'].PropTypes.func, onExited: _react2['default'].PropTypes.func }; var defaultProps = { defaultExpanded: false }; var Panel = (function (_React$Component) { _inherits(Panel, _React$Component); function Panel(props, context) { _classCallCheck(this, Panel); _React$Component.call(this, props, context); this.handleClickTitle = this.handleClickTitle.bind(this); this.state = { expanded: this.props.defaultExpanded }; } Panel.prototype.handleClickTitle = function handleClickTitle(e) { // FIXME: What the heck? This API is horrible. This needs to go away! e.persist(); e.selected = true; if (this.props.onSelect) { this.props.onSelect(this.props.eventKey, e); } else { e.preventDefault(); } if (e.selected) { this.setState({ expanded: !this.state.expanded }); } }; Panel.prototype.shouldRenderFill = function shouldRenderFill(child) { return _react2['default'].isValidElement(child) && child.props.fill != null; }; Panel.prototype.renderHeader = function renderHeader(collapsible, header, id, role, expanded, bsProps) { var titleClassName = _utilsBootstrapUtils.prefix(bsProps, 'title'); if (!collapsible) { if (!_react2['default'].isValidElement(header)) { return header; } return _react.cloneElement(header, { className: _classnames2['default'](header.props.className, titleClassName) }); } if (!_react2['default'].isValidElement(header)) { return _react2['default'].createElement( 'h4', { role: 'presentation', className: titleClassName }, this.renderAnchor(header, id, role, expanded) ); } return _react.cloneElement(header, { className: _classnames2['default'](header.props.className, titleClassName), children: this.renderAnchor(header.props.children, role) }); }; Panel.prototype.renderAnchor = function renderAnchor(header, id, role, expanded) { return _react2['default'].createElement( 'a', { role: role, href: id && '#' + id, onClick: this.handleClickTitle, 'aria-controls': id, 'aria-expanded': expanded, 'aria-selected': expanded }, header ); }; Panel.prototype.renderCollapsibleBody = function renderCollapsibleBody(id, expanded, role, children, bsProps, animationHooks) { return _react2['default'].createElement( _Collapse2['default'], _extends({ 'in': expanded }, animationHooks), _react2['default'].createElement( 'div', { id: id, role: role, className: _utilsBootstrapUtils.prefix(bsProps, 'collapse'), 'aria-hidden': !expanded }, this.renderBody(children, bsProps) ) ); }; Panel.prototype.renderBody = function renderBody(rawChildren, bsProps) { var children = []; var bodyChildren = []; var bodyClassName = _utilsBootstrapUtils.prefix(bsProps, 'body'); function maybeAddBody() { if (!bodyChildren.length) { return; } // Derive the key from the index here, since we need to make one up. children.push(_react2['default'].createElement( 'div', { key: children.length, className: bodyClassName }, bodyChildren )); bodyChildren = []; } // Convert to array so we can re-use keys. _react2['default'].Children.toArray(rawChildren).forEach(function (child) { if (_react2['default'].isValidElement(child) && child.props.fill) { maybeAddBody(); // Remove the child's unknown `fill` prop. children.push(_react.cloneElement(child, { fill: undefined })); return; } bodyChildren.push(child); }); maybeAddBody(); return children; }; Panel.prototype.render = function render() { var _props = this.props; var collapsible = _props.collapsible; var header = _props.header; var id = _props.id; var footer = _props.footer; var propsExpanded = _props.expanded; var headerRole = _props.headerRole; var panelRole = _props.panelRole; var className = _props.className; var children = _props.children; var onEnter = _props.onEnter; var onEntering = _props.onEntering; var onEntered = _props.onEntered; var onExit = _props.onExit; var onExiting = _props.onExiting; var onExited = _props.onExited; var props = _objectWithoutProperties(_props, ['collapsible', 'header', 'id', 'footer', 'expanded', 'headerRole', 'panelRole', 'className', 'children', 'onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'onExited']); var _splitBsPropsAndOmit = _utilsBootstrapUtils.splitBsPropsAndOmit(props, ['defaultExpanded', 'eventKey', 'onSelect']); var bsProps = _splitBsPropsAndOmit[0]; var elementProps = _splitBsPropsAndOmit[1]; var expanded = propsExpanded != null ? propsExpanded : this.state.expanded; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement( 'div', _extends({}, elementProps, { className: _classnames2['default'](className, classes), id: collapsible ? null : id }), header && _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils.prefix(bsProps, 'heading') }, this.renderHeader(collapsible, header, id, headerRole, expanded, bsProps) ), collapsible ? this.renderCollapsibleBody(id, expanded, panelRole, children, bsProps, { onEnter: onEnter, onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: onExited }) : this.renderBody(children, bsProps), footer && _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils.prefix(bsProps, 'footer') }, footer ) ); }; return Panel; })(_react2['default'].Component); Panel.propTypes = propTypes; Panel.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('panel', _utilsBootstrapUtils.bsStyles([].concat(_Object$values(_utilsStyleConfig.State), [_utilsStyleConfig.Style.DEFAULT, _utilsStyleConfig.Style.PRIMARY]), Panel)); module.exports = exports['default']; /***/ }, /* 200 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibIsRequiredForA11y = __webpack_require__(88); var _reactPropTypesLibIsRequiredForA11y2 = _interopRequireDefault(_reactPropTypesLibIsRequiredForA11y); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: _reactPropTypesLibIsRequiredForA11y2['default'](_react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number])), /** * Sets the direction the Popover is positioned towards. */ placement: _react2['default'].PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Popover. */ positionTop: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), /** * The "left" position value for the Popover. */ positionLeft: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), /** * Title content */ title: _react2['default'].PropTypes.node }; var defaultProps = { placement: 'right' }; var Popover = (function (_React$Component) { _inherits(Popover, _React$Component); function Popover() { _classCallCheck(this, Popover); _React$Component.apply(this, arguments); } Popover.prototype.render = function render() { var _extends2; var _props = this.props; var placement = _props.placement; var positionTop = _props.positionTop; var positionLeft = _props.positionLeft; var arrowOffsetTop = _props.arrowOffsetTop; var arrowOffsetLeft = _props.arrowOffsetLeft; var title = _props.title; var className = _props.className; var style = _props.style; var children = _props.children; var props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'title', 'className', 'style', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ display: 'block', top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return _react2['default'].createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: _classnames2['default'](className, classes), style: outerStyle }), _react2['default'].createElement('div', { className: 'arrow', style: arrowStyle }), title && _react2['default'].createElement( 'h3', { className: _utilsBootstrapUtils.prefix(bsProps, 'title') }, title ), _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils.prefix(bsProps, 'content') }, children ) ); }; return Popover; })(_react2['default'].Component); Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('popover', Popover); module.exports = exports['default']; /***/ }, /* 201 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _Object$values = __webpack_require__(45)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var ROUND_PRECISION = 1000; /** * Validate that children, if any, are instances of `<ProgressBar>`. */ function onlyProgressBar(props, propName, componentName) { var children = props[propName]; if (!children) { return null; } var error = null; _react2['default'].Children.forEach(children, function (child) { if (error) { return; } if (child.type === ProgressBar) { // eslint-disable-line no-use-before-define return; } var childIdentifier = _react2['default'].isValidElement(child) ? child.type.displayName || child.type.name || child.type : child; error = new Error('Children of ' + componentName + ' can contain only ProgressBar ' + ('components. Found ' + childIdentifier + '.')); }); return error; } var propTypes = { min: _react.PropTypes.number, now: _react.PropTypes.number, max: _react.PropTypes.number, label: _react.PropTypes.node, srOnly: _react.PropTypes.bool, striped: _react.PropTypes.bool, active: _react.PropTypes.bool, children: onlyProgressBar, /** * @private */ isChild: _react.PropTypes.bool }; var defaultProps = { min: 0, max: 100, active: false, isChild: false, srOnly: false, striped: false }; function getPercentage(now, min, max) { var percentage = (now - min) / (max - min) * 100; return Math.round(percentage * ROUND_PRECISION) / ROUND_PRECISION; } var ProgressBar = (function (_React$Component) { _inherits(ProgressBar, _React$Component); function ProgressBar() { _classCallCheck(this, ProgressBar); _React$Component.apply(this, arguments); } ProgressBar.prototype.renderProgressBar = function renderProgressBar(_ref) { var _extends2; var min = _ref.min; var now = _ref.now; var max = _ref.max; var label = _ref.label; var srOnly = _ref.srOnly; var striped = _ref.striped; var active = _ref.active; var className = _ref.className; var style = _ref.style; var props = _objectWithoutProperties(_ref, ['min', 'now', 'max', 'label', 'srOnly', 'striped', 'active', 'className', 'style']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = { active: active }, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'striped')] = active || striped, _extends2)); return _react2['default'].createElement( 'div', _extends({}, elementProps, { role: 'progressbar', className: _classnames2['default'](className, classes), style: _extends({ width: getPercentage(now, min, max) + '%' }, style), 'aria-valuenow': now, 'aria-valuemin': min, 'aria-valuemax': max }), srOnly ? _react2['default'].createElement( 'span', { className: 'sr-only' }, label ) : label ); }; ProgressBar.prototype.render = function render() { var _props = this.props; var isChild = _props.isChild; var props = _objectWithoutProperties(_props, ['isChild']); if (isChild) { return this.renderProgressBar(props); } var min = props.min; var now = props.now; var max = props.max; var label = props.label; var srOnly = props.srOnly; var striped = props.striped; var active = props.active; var bsClass = props.bsClass; var bsStyle = props.bsStyle; var className = props.className; var children = props.children; var wrapperProps = _objectWithoutProperties(props, ['min', 'now', 'max', 'label', 'srOnly', 'striped', 'active', 'bsClass', 'bsStyle', 'className', 'children']); return _react2['default'].createElement( 'div', _extends({}, wrapperProps, { className: _classnames2['default'](className, 'progress') }), children ? _utilsValidComponentChildren2['default'].map(children, function (child) { return _react.cloneElement(child, { isChild: true }); }) : this.renderProgressBar({ min: min, now: now, max: max, label: label, srOnly: srOnly, striped: striped, active: active, bsClass: bsClass, bsStyle: bsStyle }) ); }; return ProgressBar; })(_react2['default'].Component); ProgressBar.propTypes = propTypes; ProgressBar.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('progress-bar', _utilsBootstrapUtils.bsStyles(_Object$values(_utilsStyleConfig.State), ProgressBar)); module.exports = exports['default']; /***/ }, /* 202 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { inline: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, /** * Only valid if `inline` is not set. */ validationState: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Radio inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: _react2['default'].PropTypes.func }; var defaultProps = { inline: false, disabled: false }; var Radio = (function (_React$Component) { _inherits(Radio, _React$Component); function Radio() { _classCallCheck(this, Radio); _React$Component.apply(this, arguments); } Radio.prototype.render = function render() { var _props = this.props; var inline = _props.inline; var disabled = _props.disabled; var validationState = _props.validationState; var inputRef = _props.inputRef; var className = _props.className; var style = _props.style; var children = _props.children; var props = _objectWithoutProperties(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var input = _react2['default'].createElement('input', _extends({}, elementProps, { ref: inputRef, type: 'radio', disabled: disabled })); if (inline) { var _classes; var _classes2 = (_classes = {}, _classes[_utilsBootstrapUtils.prefix(bsProps, 'inline')] = true, _classes.disabled = disabled, _classes); // Use a warning here instead of in propTypes to get better-looking // generated documentation. true ? _warning2['default'](!validationState, '`validationState` is ignored on `<Radio inline>`. To display ' + 'validation state on an inline radio, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : undefined; return _react2['default'].createElement( 'label', { className: _classnames2['default'](className, _classes2), style: style }, input, children ); } var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return _react2['default'].createElement( 'div', { className: _classnames2['default'](className, classes), style: style }, _react2['default'].createElement( 'label', null, input, children ) ); }; return Radio; })(_react2['default'].Component); Radio.propTypes = propTypes; Radio.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('radio', Radio); module.exports = exports['default']; /***/ }, /* 203 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _utilsBootstrapUtils = __webpack_require__(34); // TODO: This should probably take a single `aspectRatio` prop. var propTypes = { /** * This component requires a single child element */ children: _react.PropTypes.element.isRequired, /** * 16by9 aspect ratio */ a16by9: _react.PropTypes.bool, /** * 4by3 aspect ratio */ a4by3: _react.PropTypes.bool }; var defaultProps = { a16by9: false, a4by3: false }; var ResponsiveEmbed = (function (_React$Component) { _inherits(ResponsiveEmbed, _React$Component); function ResponsiveEmbed() { _classCallCheck(this, ResponsiveEmbed); _React$Component.apply(this, arguments); } ResponsiveEmbed.prototype.render = function render() { var _extends2; var _props = this.props; var a16by9 = _props.a16by9; var a4by3 = _props.a4by3; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['a16by9', 'a4by3', 'className', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; true ? _warning2['default'](a16by9 || a4by3, 'Either `a16by9` or `a4by3` must be set.') : undefined; true ? _warning2['default'](!(a16by9 && a4by3), 'Only one of `a16by9` or `a4by3` can be set.') : undefined; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[_utilsBootstrapUtils.prefix(bsProps, '16by9')] = a16by9, _extends2[_utilsBootstrapUtils.prefix(bsProps, '4by3')] = a4by3, _extends2)); return _react2['default'].createElement( 'div', { className: _classnames2['default'](classes) }, _react.cloneElement(children, _extends({}, elementProps, { className: _classnames2['default'](className, _utilsBootstrapUtils.prefix(bsProps, 'item')) })) ); }; return ResponsiveEmbed; })(_react2['default'].Component); ResponsiveEmbed.propTypes = propTypes; ResponsiveEmbed.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('embed-responsive', ResponsiveEmbed); module.exports = exports['default']; /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'] }; var defaultProps = { componentClass: 'div' }; var Row = (function (_React$Component) { _inherits(Row, _React$Component); function Row() { _classCallCheck(this, Row); _React$Component.apply(this, arguments); } Row.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Row; })(_react2['default'].Component); Row.propTypes = propTypes; Row.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('row', Row); module.exports = exports['default']; /***/ }, /* 205 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(20)['default']; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _Button = __webpack_require__(54); var _Button2 = _interopRequireDefault(_Button); var _Dropdown = __webpack_require__(83); var _Dropdown2 = _interopRequireDefault(_Dropdown); var _SplitToggle = __webpack_require__(206); var _SplitToggle2 = _interopRequireDefault(_SplitToggle); var _utilsSplitComponentProps = __webpack_require__(126); var _utilsSplitComponentProps2 = _interopRequireDefault(_utilsSplitComponentProps); var propTypes = _extends({}, _Dropdown2['default'].propTypes, { // Toggle props. bsStyle: _react2['default'].PropTypes.string, bsSize: _react2['default'].PropTypes.string, href: _react2['default'].PropTypes.string, onClick: _react2['default'].PropTypes.func, /** * The content of the split button. */ title: _react2['default'].PropTypes.node.isRequired, /** * Accessible label for the toggle; the value of `title` if not specified. */ toggleLabel: _react2['default'].PropTypes.string, // Override generated docs from <Dropdown>. /** * @private */ children: _react2['default'].PropTypes.node }); var SplitButton = (function (_React$Component) { _inherits(SplitButton, _React$Component); function SplitButton() { _classCallCheck(this, SplitButton); _React$Component.apply(this, arguments); } SplitButton.prototype.render = function render() { var _props = this.props; var bsSize = _props.bsSize; var bsStyle = _props.bsStyle; var title = _props.title; var toggleLabel = _props.toggleLabel; var children = _props.children; var props = _objectWithoutProperties(_props, ['bsSize', 'bsStyle', 'title', 'toggleLabel', 'children']); var _splitComponentProps = _utilsSplitComponentProps2['default'](props, _Dropdown2['default'].ControlledComponent); var dropdownProps = _splitComponentProps[0]; var buttonProps = _splitComponentProps[1]; return _react2['default'].createElement( _Dropdown2['default'], _extends({}, dropdownProps, { bsSize: bsSize, bsStyle: bsStyle }), _react2['default'].createElement( _Button2['default'], _extends({}, buttonProps, { disabled: props.disabled, bsSize: bsSize, bsStyle: bsStyle }), title ), _react2['default'].createElement(_SplitToggle2['default'], { 'aria-label': toggleLabel || title, bsSize: bsSize, bsStyle: bsStyle }), _react2['default'].createElement( _Dropdown2['default'].Menu, null, children ) ); }; return SplitButton; })(_react2['default'].Component); SplitButton.propTypes = propTypes; SplitButton.Toggle = _SplitToggle2['default']; exports['default'] = SplitButton; module.exports = exports['default']; /***/ }, /* 206 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _DropdownToggle = __webpack_require__(123); var _DropdownToggle2 = _interopRequireDefault(_DropdownToggle); var SplitToggle = (function (_React$Component) { _inherits(SplitToggle, _React$Component); function SplitToggle() { _classCallCheck(this, SplitToggle); _React$Component.apply(this, arguments); } SplitToggle.prototype.render = function render() { return _react2['default'].createElement(_DropdownToggle2['default'], _extends({}, this.props, { useAnchor: false, noCaret: false })); }; return SplitToggle; })(_react2['default'].Component); SplitToggle.defaultProps = _DropdownToggle2['default'].defaultProps; exports['default'] = SplitToggle; module.exports = exports['default']; /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(20)['default']; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _TabContainer = __webpack_require__(208); var _TabContainer2 = _interopRequireDefault(_TabContainer); var _TabContent = __webpack_require__(209); var _TabContent2 = _interopRequireDefault(_TabContent); var _TabPane = __webpack_require__(210); var _TabPane2 = _interopRequireDefault(_TabPane); var propTypes = _extends({}, _TabPane2['default'].propTypes, { disabled: _react2['default'].PropTypes.bool, title: _react2['default'].PropTypes.node, /** * tabClassName is used as className for the associated NavItem */ tabClassName: _react2['default'].PropTypes.string }); var Tab = (function (_React$Component) { _inherits(Tab, _React$Component); function Tab() { _classCallCheck(this, Tab); _React$Component.apply(this, arguments); } Tab.prototype.render = function render() { var props = _extends({}, this.props); // These props are for the parent `<Tabs>` rather than the `<TabPane>`. delete props.title; delete props.disabled; delete props.tabClassName; return _react2['default'].createElement(_TabPane2['default'], props); }; return Tab; })(_react2['default'].Component); Tab.propTypes = propTypes; Tab.Container = _TabContainer2['default']; Tab.Content = _TabContent2['default']; Tab.Pane = _TabPane2['default']; exports['default'] = Tab; module.exports = exports['default']; /***/ }, /* 208 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _uncontrollable = __webpack_require__(89); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var TAB = 'tab'; var PANE = 'pane'; var idPropType = _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]); var propTypes = { /** * HTML id attribute, required if no `generateChildId` prop * is specified. */ id: function id(props) { var error = null; if (!props.generateChildId) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } error = idPropType.apply(undefined, [props].concat(args)); if (!error && !props.id) { error = new Error('In order to properly initialize Tabs in a way that is accessible ' + 'to assistive technologies (such as screen readers) an `id` or a ' + '`generateChildId` prop to TabContainer is required'); } } return error; }, /** * A function that takes an `eventKey` and `type` and returns a unique id for * child tab `<NavItem>`s and `<TabPane>`s. The function _must_ be a pure * function, meaning it should always return the _same_ id for the same set * of inputs. The default value requires that an `id` to be set for the * `<TabContainer>`. * * The `type` argument will either be `"tab"` or `"pane"`. * * @defaultValue (eventKey, type) => `${this.props.id}-${type}-${key}` */ generateChildId: _react.PropTypes.func, /** * A callback fired when a tab is selected. * * @controllable activeKey */ onSelect: _react.PropTypes.func, /** * The `eventKey` of the currently active tab. * * @controllable onSelect */ activeKey: _react.PropTypes.any }; var childContextTypes = { $bs_tabContainer: _react2['default'].PropTypes.shape({ activeKey: _react.PropTypes.any, onSelect: _react.PropTypes.func.isRequired, getTabId: _react.PropTypes.func.isRequired, getPaneId: _react.PropTypes.func.isRequired }) }; var TabContainer = (function (_React$Component) { _inherits(TabContainer, _React$Component); function TabContainer() { _classCallCheck(this, TabContainer); _React$Component.apply(this, arguments); } TabContainer.prototype.getChildContext = function getChildContext() { var _props = this.props; var activeKey = _props.activeKey; var onSelect = _props.onSelect; var generateChildId = _props.generateChildId; var id = _props.id; var getId = generateChildId || function (key, type) { return id ? id + '-' + type + '-' + key : null; }; return { $bs_tabContainer: { activeKey: activeKey, onSelect: onSelect, getTabId: function getTabId(key) { return getId(key, TAB); }, getPaneId: function getPaneId(key) { return getId(key, PANE); } } }; }; TabContainer.prototype.render = function render() { var _props2 = this.props; var children = _props2.children; var props = _objectWithoutProperties(_props2, ['children']); delete props.generateChildId; delete props.onSelect; delete props.activeKey; return _react2['default'].cloneElement(_react2['default'].Children.only(children), props); }; return TabContainer; })(_react2['default'].Component); TabContainer.propTypes = propTypes; TabContainer.childContextTypes = childContextTypes; exports['default'] = _uncontrollable2['default'](TabContainer, { activeKey: 'onSelect' }); module.exports = exports['default']; /***/ }, /* 209 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { componentClass: _reactPropTypesLibElementType2['default'], /** * Sets a default animation strategy for all children `<TabPane>`s. Use * `false` to disable, `true` to enable the default `<Fade>` animation or any * `<Transition>` component. */ animation: _react.PropTypes.oneOfType([_react.PropTypes.bool, _reactPropTypesLibElementType2['default']]), /** * Unmount tabs (remove it from the DOM) when they are no longer visible */ unmountOnExit: _react.PropTypes.bool }; var defaultProps = { componentClass: 'div', animation: true, unmountOnExit: false }; var contextTypes = { $bs_tabContainer: _react.PropTypes.shape({ activeKey: _react.PropTypes.any }) }; var childContextTypes = { $bs_tabContent: _react.PropTypes.shape({ bsClass: _react.PropTypes.string, animation: _react.PropTypes.oneOfType([_react.PropTypes.bool, _reactPropTypesLibElementType2['default']]), activeKey: _react.PropTypes.any, unmountOnExit: _react.PropTypes.bool, onPaneEnter: _react.PropTypes.func.isRequired, onPaneExited: _react.PropTypes.func.isRequired, exiting: _react.PropTypes.bool.isRequired }) }; var TabContent = (function (_React$Component) { _inherits(TabContent, _React$Component); function TabContent(props, context) { _classCallCheck(this, TabContent); _React$Component.call(this, props, context); this.handlePaneEnter = this.handlePaneEnter.bind(this); this.handlePaneExited = this.handlePaneExited.bind(this); // Active entries in state will be `null` unless `animation` is set. Need // to track active child in case keys swap and the active child changes // but the active key does not. this.state = { activeKey: null, activeChild: null }; } TabContent.prototype.getChildContext = function getChildContext() { var _props = this.props; var bsClass = _props.bsClass; var animation = _props.animation; var unmountOnExit = _props.unmountOnExit; var stateActiveKey = this.state.activeKey; var containerActiveKey = this.getContainerActiveKey(); var activeKey = stateActiveKey != null ? stateActiveKey : containerActiveKey; var exiting = stateActiveKey != null && stateActiveKey !== containerActiveKey; return { $bs_tabContent: { bsClass: bsClass, animation: animation, activeKey: activeKey, unmountOnExit: unmountOnExit, onPaneEnter: this.handlePaneEnter, onPaneExited: this.handlePaneExited, exiting: exiting } }; }; TabContent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (!nextProps.animation && this.state.activeChild) { this.setState({ activeKey: null, activeChild: null }); } }; TabContent.prototype.componentWillUnmount = function componentWillUnmount() { this.isUnmounted = true; }; TabContent.prototype.handlePaneEnter = function handlePaneEnter(child, childKey) { if (!this.props.animation) { return false; } // It's possible that this child should be transitioning out. if (childKey !== this.getContainerActiveKey()) { return false; } this.setState({ activeKey: childKey, activeChild: child }); return true; }; TabContent.prototype.handlePaneExited = function handlePaneExited(child) { // This might happen as everything is unmounting. if (this.isUnmounted) { return; } this.setState(function (_ref) { var activeChild = _ref.activeChild; if (activeChild !== child) { return null; } return { activeKey: null, activeChild: null }; }); }; TabContent.prototype.getContainerActiveKey = function getContainerActiveKey() { var tabContainer = this.context.$bs_tabContainer; return tabContainer && tabContainer.activeKey; }; TabContent.prototype.render = function render() { var _props2 = this.props; var Component = _props2.componentClass; var className = _props2.className; var props = _objectWithoutProperties(_props2, ['componentClass', 'className']); var _splitBsPropsAndOmit = _utilsBootstrapUtils.splitBsPropsAndOmit(props, ['animation', 'unmountOnExit']); var bsProps = _splitBsPropsAndOmit[0]; var elementProps = _splitBsPropsAndOmit[1]; return _react2['default'].createElement(Component, _extends({}, elementProps, { className: _classnames2['default'](className, _utilsBootstrapUtils.prefix(bsProps, 'content')) })); }; return TabContent; })(_react2['default'].Component); TabContent.propTypes = propTypes; TabContent.defaultProps = defaultProps; TabContent.contextTypes = contextTypes; TabContent.childContextTypes = childContextTypes; exports['default'] = _utilsBootstrapUtils.bsClass('tab', TabContent); module.exports = exports['default']; /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(52); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _warning = __webpack_require__(65); var _warning2 = _interopRequireDefault(_warning); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsCreateChainedFunction = __webpack_require__(42); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _Fade = __webpack_require__(127); var _Fade2 = _interopRequireDefault(_Fade); var propTypes = { /** * Uniquely identify the `<TabPane>` among its siblings. */ eventKey: _react.PropTypes.any, /** * Use animation when showing or hiding `<TabPane>`s. Use `false` to disable, * `true` to enable the default `<Fade>` animation or any `<Transition>` * component. */ animation: _react.PropTypes.oneOfType([_react.PropTypes.bool, _reactPropTypesLibElementType2['default']]), /** @private **/ id: _react.PropTypes.string, /** @private **/ 'aria-labelledby': _react.PropTypes.string, /** * If not explicitly specified and rendered in the context of a * `<TabContent>`, the `bsClass` of the `<TabContent>` suffixed by `-pane`. * If otherwise not explicitly specified, `tab-pane`. */ bsClass: _react2['default'].PropTypes.string, /** * Transition onEnter callback when animation is not `false` */ onEnter: _react.PropTypes.func, /** * Transition onEntering callback when animation is not `false` */ onEntering: _react.PropTypes.func, /** * Transition onEntered callback when animation is not `false` */ onEntered: _react.PropTypes.func, /** * Transition onExit callback when animation is not `false` */ onExit: _react.PropTypes.func, /** * Transition onExiting callback when animation is not `false` */ onExiting: _react.PropTypes.func, /** * Transition onExited callback when animation is not `false` */ onExited: _react.PropTypes.func, /** * Unmount the tab (remove it from the DOM) when it is no longer visible */ unmountOnExit: _react.PropTypes.bool }; var contextTypes = { $bs_tabContainer: _react.PropTypes.shape({ getId: _react.PropTypes.func, unmountOnExit: _react.PropTypes.bool }), $bs_tabContent: _react.PropTypes.shape({ bsClass: _react.PropTypes.string, animation: _react.PropTypes.oneOfType([_react.PropTypes.bool, _reactPropTypesLibElementType2['default']]), activeKey: _react.PropTypes.any, unmountOnExit: _react.PropTypes.bool, onPaneEnter: _react.PropTypes.func.isRequired, onPaneExited: _react.PropTypes.func.isRequired, exiting: _react.PropTypes.bool.isRequired }) }; /** * We override the `<TabContainer>` context so `<Nav>`s in `<TabPane>`s don't * conflict with the top level one. */ var childContextTypes = { $bs_tabContainer: _react.PropTypes.oneOf([null]) }; var TabPane = (function (_React$Component) { _inherits(TabPane, _React$Component); function TabPane(props, context) { _classCallCheck(this, TabPane); _React$Component.call(this, props, context); this.handleEnter = this.handleEnter.bind(this); this.handleExited = this.handleExited.bind(this); this['in'] = false; } TabPane.prototype.getChildContext = function getChildContext() { return { $bs_tabContainer: null }; }; TabPane.prototype.componentDidMount = function componentDidMount() { if (this.shouldBeIn()) { // In lieu of the action event firing. this.handleEnter(); } }; TabPane.prototype.componentDidUpdate = function componentDidUpdate() { if (this['in']) { if (!this.shouldBeIn()) { // We shouldn't be active any more. Notify the parent. this.handleExited(); } } else if (this.shouldBeIn()) { // We are the active child. Notify the parent. this.handleEnter(); } }; TabPane.prototype.componentWillUnmount = function componentWillUnmount() { if (this['in']) { // In lieu of the action event firing. this.handleExited(); } }; TabPane.prototype.handleEnter = function handleEnter() { var tabContent = this.context.$bs_tabContent; if (!tabContent) { return; } this['in'] = tabContent.onPaneEnter(this, this.props.eventKey); }; TabPane.prototype.handleExited = function handleExited() { var tabContent = this.context.$bs_tabContent; if (!tabContent) { return; } tabContent.onPaneExited(this); this['in'] = false; }; TabPane.prototype.getAnimation = function getAnimation() { if (this.props.animation != null) { return this.props.animation; } var tabContent = this.context.$bs_tabContent; return tabContent && tabContent.animation; }; TabPane.prototype.isActive = function isActive() { var tabContent = this.context.$bs_tabContent; var activeKey = tabContent && tabContent.activeKey; return this.props.eventKey === activeKey; }; TabPane.prototype.shouldBeIn = function shouldBeIn() { return this.getAnimation() && this.isActive(); }; TabPane.prototype.render = function render() { var _props = this.props; var eventKey = _props.eventKey; var className = _props.className; var onEnter = _props.onEnter; var onEntering = _props.onEntering; var onEntered = _props.onEntered; var onExit = _props.onExit; var onExiting = _props.onExiting; var onExited = _props.onExited; var propsUnmountOnExit = _props.unmountOnExit; var props = _objectWithoutProperties(_props, ['eventKey', 'className', 'onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'onExited', 'unmountOnExit']); var _context = this.context; var tabContent = _context.$bs_tabContent; var tabContainer = _context.$bs_tabContainer; var _splitBsPropsAndOmit = _utilsBootstrapUtils.splitBsPropsAndOmit(props, ['animation']); var bsProps = _splitBsPropsAndOmit[0]; var elementProps = _splitBsPropsAndOmit[1]; var active = this.isActive(); var animation = this.getAnimation(); var unmountOnExit = propsUnmountOnExit != null ? propsUnmountOnExit : tabContent && tabContent.unmountOnExit; if (!active && !animation && unmountOnExit) { return null; } var Transition = animation === true ? _Fade2['default'] : animation || null; if (tabContent) { bsProps.bsClass = _utilsBootstrapUtils.prefix(tabContent, 'pane'); } var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), { active: active }); if (tabContainer) { true ? _warning2['default'](!elementProps.id && !elementProps['aria-labelledby'], 'In the context of a `<TabContainer>`, `<TabPanes>` are given ' + 'generated `id` and `aria-labelledby` attributes for the sake of ' + 'proper component accessibility. Any provided ones will be ignored. ' + 'To control these attributes directly provide a `generateChildId` ' + 'prop to the parent `<TabContainer>`.') : undefined; elementProps.id = tabContainer.getPaneId(eventKey); elementProps['aria-labelledby'] = tabContainer.getTabId(eventKey); } var pane = _react2['default'].createElement('div', _extends({}, elementProps, { role: 'tabpanel', 'aria-hidden': !active, className: _classnames2['default'](className, classes) })); if (Transition) { var exiting = tabContent && tabContent.exiting; return _react2['default'].createElement( Transition, { 'in': active && !exiting, onEnter: _utilsCreateChainedFunction2['default'](this.handleEnter, onEnter), onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: _utilsCreateChainedFunction2['default'](this.handleExited, onExited), unmountOnExit: unmountOnExit }, pane ); } return pane; }; return TabPane; })(_react2['default'].Component); TabPane.propTypes = propTypes; TabPane.contextTypes = contextTypes; TabPane.childContextTypes = childContextTypes; exports['default'] = _utilsBootstrapUtils.bsClass('tab-pane', TabPane); module.exports = exports['default']; /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { striped: _react2['default'].PropTypes.bool, bordered: _react2['default'].PropTypes.bool, condensed: _react2['default'].PropTypes.bool, hover: _react2['default'].PropTypes.bool, responsive: _react2['default'].PropTypes.bool }; var defaultProps = { bordered: false, condensed: false, hover: false, responsive: false, striped: false }; var Table = (function (_React$Component) { _inherits(Table, _React$Component); function Table() { _classCallCheck(this, Table); _React$Component.apply(this, arguments); } Table.prototype.render = function render() { var _extends2; var _props = this.props; var striped = _props.striped; var bordered = _props.bordered; var condensed = _props.condensed; var hover = _props.hover; var responsive = _props.responsive; var className = _props.className; var props = _objectWithoutProperties(_props, ['striped', 'bordered', 'condensed', 'hover', 'responsive', 'className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'striped')] = striped, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'bordered')] = bordered, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'condensed')] = condensed, _extends2[_utilsBootstrapUtils.prefix(bsProps, 'hover')] = hover, _extends2)); var table = _react2['default'].createElement('table', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); if (responsive) { return _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils.prefix(bsProps, 'responsive') }, table ); } return table; }; return Table; })(_react2['default'].Component); Table.propTypes = propTypes; Table.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('table', Table); module.exports = exports['default']; /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibIsRequiredForA11y = __webpack_require__(88); var _reactPropTypesLibIsRequiredForA11y2 = _interopRequireDefault(_reactPropTypesLibIsRequiredForA11y); var _uncontrollable = __webpack_require__(89); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _Nav = __webpack_require__(174); var _Nav2 = _interopRequireDefault(_Nav); var _NavItem = __webpack_require__(181); var _NavItem2 = _interopRequireDefault(_NavItem); var _TabContainer = __webpack_require__(208); var _TabContainer2 = _interopRequireDefault(_TabContainer); var _TabContent = __webpack_require__(209); var _TabContent2 = _interopRequireDefault(_TabContent); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsValidComponentChildren = __webpack_require__(43); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var TabContainer = _TabContainer2['default'].ControlledComponent; var propTypes = { /** * Mark the Tab with a matching `eventKey` as active. * * @controllable onSelect */ activeKey: _react2['default'].PropTypes.any, /** * Navigation style */ bsStyle: _react2['default'].PropTypes.oneOf(['tabs', 'pills']), animation: _react2['default'].PropTypes.bool, id: _reactPropTypesLibIsRequiredForA11y2['default'](_react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number])), /** * Callback fired when a Tab is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` * * @controllable activeKey */ onSelect: _react2['default'].PropTypes.func, /** * Unmount tabs (remove it from the DOM) when it is no longer visible */ unmountOnExit: _react2['default'].PropTypes.bool }; var defaultProps = { bsStyle: 'tabs', animation: true, unmountOnExit: false }; function getDefaultActiveKey(children) { var defaultActiveKey = undefined; _utilsValidComponentChildren2['default'].forEach(children, function (child) { if (defaultActiveKey == null) { defaultActiveKey = child.props.eventKey; } }); return defaultActiveKey; } var Tabs = (function (_React$Component) { _inherits(Tabs, _React$Component); function Tabs() { _classCallCheck(this, Tabs); _React$Component.apply(this, arguments); } Tabs.prototype.renderTab = function renderTab(child) { var _child$props = child.props; var title = _child$props.title; var eventKey = _child$props.eventKey; var disabled = _child$props.disabled; var tabClassName = _child$props.tabClassName; if (title == null) { return null; } return _react2['default'].createElement( _NavItem2['default'], { eventKey: eventKey, disabled: disabled, className: tabClassName }, title ); }; Tabs.prototype.render = function render() { var _props = this.props; var id = _props.id; var onSelect = _props.onSelect; var animation = _props.animation; var unmountOnExit = _props.unmountOnExit; var bsClass = _props.bsClass; var className = _props.className; var style = _props.style; var children = _props.children; var _props$activeKey = _props.activeKey; var activeKey = _props$activeKey === undefined ? getDefaultActiveKey(children) : _props$activeKey; var props = _objectWithoutProperties(_props, ['id', 'onSelect', 'animation', 'unmountOnExit', 'bsClass', 'className', 'style', 'children', 'activeKey']); return _react2['default'].createElement( TabContainer, { id: id, activeKey: activeKey, onSelect: onSelect, className: className, style: style }, _react2['default'].createElement( 'div', null, _react2['default'].createElement( _Nav2['default'], _extends({}, props, { role: 'tablist' }), _utilsValidComponentChildren2['default'].map(children, this.renderTab) ), _react2['default'].createElement( _TabContent2['default'], { bsClass: bsClass, animation: animation, unmountOnExit: unmountOnExit }, children ) ) ); }; return Tabs; })(_react2['default'].Component); Tabs.propTypes = propTypes; Tabs.defaultProps = defaultProps; _utilsBootstrapUtils.bsClass('tab', Tabs); exports['default'] = _uncontrollable2['default'](Tabs, { activeKey: 'onSelect' }); module.exports = exports['default']; /***/ }, /* 213 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _SafeAnchor = __webpack_require__(51); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { src: _react2['default'].PropTypes.string, alt: _react2['default'].PropTypes.string, href: _react2['default'].PropTypes.string }; var Thumbnail = (function (_React$Component) { _inherits(Thumbnail, _React$Component); function Thumbnail() { _classCallCheck(this, Thumbnail); _React$Component.apply(this, arguments); } Thumbnail.prototype.render = function render() { var _props = this.props; var src = _props.src; var alt = _props.alt; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['src', 'alt', 'className', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var Component = elementProps.href ? _SafeAnchor2['default'] : 'div'; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement( Component, _extends({}, elementProps, { className: _classnames2['default'](className, classes) }), _react2['default'].createElement('img', { src: src, alt: alt }), children && _react2['default'].createElement( 'div', { className: 'caption' }, children ) ); }; return Thumbnail; })(_react2['default'].Component); Thumbnail.propTypes = propTypes; exports['default'] = _utilsBootstrapUtils.bsClass('thumbnail', Thumbnail); module.exports = exports['default']; /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _extends = __webpack_require__(20)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibIsRequiredForA11y = __webpack_require__(88); var _reactPropTypesLibIsRequiredForA11y2 = _interopRequireDefault(_reactPropTypesLibIsRequiredForA11y); var _utilsBootstrapUtils = __webpack_require__(34); var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string|number} * @required */ id: _reactPropTypesLibIsRequiredForA11y2['default'](_react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number])), /** * Sets the direction the Tooltip is positioned towards. */ placement: _react2['default'].PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Tooltip. */ positionTop: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), /** * The "left" position value for the Tooltip. */ positionLeft: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]) }; var defaultProps = { placement: 'right' }; var Tooltip = (function (_React$Component) { _inherits(Tooltip, _React$Component); function Tooltip() { _classCallCheck(this, Tooltip); _React$Component.apply(this, arguments); } Tooltip.prototype.render = function render() { var _extends2; var _props = this.props; var placement = _props.placement; var positionTop = _props.positionTop; var positionLeft = _props.positionLeft; var arrowOffsetTop = _props.arrowOffsetTop; var arrowOffsetLeft = _props.arrowOffsetLeft; var className = _props.className; var style = _props.style; var children = _props.children; var props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, _utilsBootstrapUtils.getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return _react2['default'].createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: _classnames2['default'](className, classes), style: outerStyle }), _react2['default'].createElement('div', { className: _utilsBootstrapUtils.prefix(bsProps, 'arrow'), style: arrowStyle }), _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils.prefix(bsProps, 'inner') }, children ) ); }; return Tooltip; })(_react2['default'].Component); Tooltip.propTypes = propTypes; Tooltip.defaultProps = defaultProps; exports['default'] = _utilsBootstrapUtils.bsClass('tooltip', Tooltip); module.exports = exports['default']; /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(4)['default']; var _classCallCheck = __webpack_require__(19)['default']; var _objectWithoutProperties = __webpack_require__(32)['default']; var _extends = __webpack_require__(20)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(33); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(30); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(34); var _utilsStyleConfig = __webpack_require__(41); var Well = (function (_React$Component) { _inherits(Well, _React$Component); function Well() { _classCallCheck(this, Well); _React$Component.apply(this, arguments); } Well.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = _utilsBootstrapUtils.splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _utilsBootstrapUtils.getClassSet(bsProps); return _react2['default'].createElement('div', _extends({}, elementProps, { className: _classnames2['default'](className, classes) })); }; return Well; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('well', _utilsBootstrapUtils.bsSizes([_utilsStyleConfig.Size.LARGE, _utilsStyleConfig.Size.SMALL], Well)); module.exports = exports['default']; /***/ }, /* 216 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireWildcard = __webpack_require__(2)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _bootstrapUtils2 = __webpack_require__(34); var _bootstrapUtils = _interopRequireWildcard(_bootstrapUtils2); exports.bootstrapUtils = _bootstrapUtils; var _createChainedFunction2 = __webpack_require__(42); var _createChainedFunction3 = _interopRequireDefault(_createChainedFunction2); exports.createChainedFunction = _createChainedFunction3['default']; var _ValidComponentChildren2 = __webpack_require__(43); var _ValidComponentChildren3 = _interopRequireDefault(_ValidComponentChildren2); exports.ValidComponentChildren = _ValidComponentChildren3['default']; /***/ } /******/ ]) }); ;
src/controls/videofield/videofield.js
thinktopography/reframe
import Buttons from '../../components/buttons' import Button from '../../components/button' import PropTypes from 'prop-types' import Picker from './picker' import React from 'react' class VideoField extends React.Component{ static contextTypes = { form: PropTypes.object } static propTypes = { defaultValue: PropTypes.number, src: PropTypes.string, link_id: PropTypes.number, onFetchLink: PropTypes.func, onCreateLink: PropTypes.func, onReady: PropTypes.func } _handlePicker = this._handlePicker.bind(this) _handleRemove = this._handleRemove.bind(this) _handleSet = this._handleSet.bind(this) render() { const { src } = this.props if(!src) return <Button { ...this._getNewButton() } /> return ( <div className="reframe-videofield"> <div className="reframe-videofield-player"> <iframe { ...this._getIframe()} /> </div> <div className="reframe-videofield-footer"> <Buttons { ...this._getEditButtons() } /> </div> </div> ) } componentDidMount() { const { defaultValue, onReady, onFetchLink } = this.props if(defaultValue) onFetchLink(defaultValue) if(onReady) onReady() } componentDidUpdate(prevProps) { const { link_id, onChange } = this.props if(link_id !== prevProps.link_id) { onChange(link_id) } } _getIframe() { const { src } = this.props return { src, frameBorder: 0, allowFullScreen: true } } _getPicker() { const { cid, onCreateLink } = this.props return { cid, onCreateLink } } _getEditButtons() { return { buttons: [ { label: 'Remove', color: 'red', handler: this._handleRemove },{ label: 'Change', color: 'green', handler: this._handlePicker } ] } } _getNewButton() { return { className: 'ui blue button', label: 'Embed Video', handler: this._handlePicker } } _handlePicker() { this.context.form.push(<Picker { ...this._getPicker() } />) } _handleRemove() { this.props.onRemove() } _handleSet(src) { this.props.onSet(src) } } export default VideoField
client/store/actions.js
Satyam/RoxyMusic
export * from './albums/actions'; export * from './artists/actions'; export * from './songs/actions'; export * from './playLists/actions'; export * from './requests/actions'; export * from './tracks/actions'; export * from './nowPlaying/actions'; export * from './config/actions'; export * from './sync/actions'; export { push, replace, go, goBack, goForward } from 'react-router-redux';
tests/layouts/CoreLayout.spec.js
prashantpawar/blockapps-js-tutorial
import React from 'react' import TestUtils from 'react-addons-test-utils' import CoreLayout from 'layouts/CoreLayout' function shallowRender (component) { const renderer = TestUtils.createRenderer() renderer.render(component) return renderer.getRenderOutput() } function shallowRenderWithProps (props = {}) { return shallowRender(<CoreLayout {...props} />) } describe('(Layout) Core', function () { let _component let _props let _child beforeEach(function () { _child = <h1 className='child'>Child</h1> _props = { children: _child } _component = shallowRenderWithProps(_props) }) it('Should render as a <div>.', function () { expect(_component.type).to.equal('div') }) })
packages/reactor-kitchensink/src/examples/Charts/3DColumn/NegativeValues/NegativeValues.js
markbrocato/extjs-reactor
import React, { Component } from 'react'; import { Container } from '@extjs/ext-react'; import { Cartesian } from '@extjs/ext-react-charts'; import ChartToolbar from '../../ChartToolbar'; export default class NegativeValues extends Component { store = Ext.create('Ext.data.Store', { fields: ['quarter', 'consumer', 'gaming', 'phone', 'corporate'], data: [ { quarter: 'Q1 2012', consumer: 7, gaming: 3, phone: 5, corporate: -7}, { quarter: 'Q2 2012', consumer: 7, gaming: 4, phone: 6, corporate: -4}, { quarter: 'Q3 2012', consumer: 8, gaming: 5, phone: 7, corporate: -3}, { quarter: 'Q4 2012', consumer: 10, gaming: 3, phone: 8, corporate: -1}, { quarter: 'Q1 2013', consumer: 6, gaming: 1, phone: 7, corporate: -2}, { quarter: 'Q2 2013', consumer: 7, gaming: -4, phone: 8, corporate: -1}, { quarter: 'Q3 2013', consumer: 8, gaming: -6, phone: 9, corporate: 0 }, { quarter: 'Q4 2013', consumer: 10, gaming: -3, phone: 11, corporate: 2 }, { quarter: 'Q1 2014', consumer: 6, gaming: 2, phone: 9, corporate: -1}, { quarter: 'Q2 2014', consumer: 6, gaming: 6, phone: 10, corporate: -6}, { quarter: 'Q3 2014', consumer: 8, gaming: 9, phone: 12, corporate: -7}, { quarter: 'Q4 2014', consumer: 9, gaming: 11, phone: 11, corporate: -4} ] }) onSeriesRender = (sprite, config, data, index) => { const isNegative = data.store.getAt(index).get('gaming') < 0; if (isNegative) { return { fillStyle: '#974144' // dark red }; } } render() { return ( <Container padding={!Ext.os.is.Phone && 10} layout="fit"> <ChartToolbar downloadChartRef={this.refs.chart}/> <Cartesian shadow ref="chart" theme="muted" store={this.store} insetPadding="40 40 20 20" innerPadding="0 3 0 0" interactions="itemhighlight" animation={{ easing: 'backOut', duration: 500 }} axes={[{ type: 'numeric3d', position: 'left', fields: 'gaming', grid: { odd: { fillStyle: 'rgba(255, 255, 255, 0.06)' }, even: { fillStyle: 'rgba(0, 0, 0, 0.05)' } } }, { type: 'category3d', position: 'bottom', fields: 'quarter', grid: true, label: { rotate: { degrees: -60 } } }]} series={[{ type: 'bar3d', xField: 'quarter', yField: 'gaming', highlight: true, renderer: this.onSeriesRender }]} /> </Container> ) } }
web/src/components/Loading.js
slice/dogbot
import React from 'react' import styled, { keyframes } from 'styled-components' const loadingAnimation = keyframes` 0% { transform: scale(1); } 50% { transform: scale(0.5); } 100% { transform: scale(1); } ` export const Pulser = styled.div` display: inline-block; width: 2rem; height: 2rem; border-radius: 100%; background: ${(props) => props.theme.accent}; animation: 1s ease infinite ${loadingAnimation}; ` const StyledLoading = styled.div` display: inline-flex; align-items: center; margin: 1rem 0; ` const LoadingText = styled.div` margin-left: 1rem; text-transform: uppercase; font-size: 0.8rem; ` export default function Loading() { return ( <StyledLoading> <Pulser /> <LoadingText>Loading...</LoadingText> </StyledLoading> ) }
step4-router/node_modules/react-router/modules/IndexRoute.js
jintoppy/react-training
import React from 'react' import warning from './routerWarning' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { component, components, falsy } from './PropTypes' const { func } = React.PropTypes /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ const IndexRoute = React.createClass({ statics: { createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = createRouteFromReactElement(element) } else { warning( false, 'An <IndexRoute> does not make sense at the root of your route config' ) } } }, propTypes: { path: falsy, component, components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render() { invariant( false, '<IndexRoute> elements are for router configuration only and should not be rendered' ) } }) export default IndexRoute
node_modules/react-bootstrap/es/SafeAnchor.js
rblin081/drafting-client
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import elementType from 'prop-types-extra/lib/elementType'; var propTypes = { href: PropTypes.string, onClick: PropTypes.func, disabled: PropTypes.bool, role: PropTypes.string, tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * this is sort of silly but needed for Button */ componentClass: elementType }; var defaultProps = { componentClass: 'a' }; function isTrivialHref(href) { return !href || href.trim() === '#'; } /** * There are situations due to browser quirks or Bootstrap CSS where * an anchor tag is needed, when semantically a button tag is the * better choice. SafeAnchor ensures that when an anchor is used like a * button its accessible. It also emulates input `disabled` behavior for * links, which is usually desirable for Buttons, NavItems, MenuItems, etc. */ var SafeAnchor = function (_React$Component) { _inherits(SafeAnchor, _React$Component); function SafeAnchor(props, context) { _classCallCheck(this, SafeAnchor); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } SafeAnchor.prototype.handleClick = function handleClick(event) { var _props = this.props, disabled = _props.disabled, href = _props.href, onClick = _props.onClick; if (disabled || isTrivialHref(href)) { event.preventDefault(); } if (disabled) { event.stopPropagation(); return; } if (onClick) { onClick(event); } }; SafeAnchor.prototype.render = function render() { var _props2 = this.props, Component = _props2.componentClass, disabled = _props2.disabled, props = _objectWithoutProperties(_props2, ['componentClass', 'disabled']); if (isTrivialHref(props.href)) { props.role = props.role || 'button'; // we want to make sure there is a href attribute on the node // otherwise, the cursor incorrectly styled (except with role='button') props.href = props.href || '#'; } if (disabled) { props.tabIndex = -1; props.style = _extends({ pointerEvents: 'none' }, props.style); } return React.createElement(Component, _extends({}, props, { onClick: this.handleClick })); }; return SafeAnchor; }(React.Component); SafeAnchor.propTypes = propTypes; SafeAnchor.defaultProps = defaultProps; export default SafeAnchor;
UserSide/scripts/jquery.js
jassimran/WWCATL_PublicDefenders
/*! * jQuery JavaScript Library v1.12.3 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-04-05T19:16Z */ (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 have a `window` with a `document` // (such as Node.js), expose a 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 ) { // Support: Firefox 18+ // Can't be in strict mode, several libs including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) //"use strict"; var deletedIds = []; var document = window.document; 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.12.3", // 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. each: function( callback ) { return jQuery.each( this, callback ); }, 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(); }, // 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 // adding 1 corrects loss of precision from parseFloat (#15100) var realStringObj = obj && obj.toString(); return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 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.ownFirst ) { 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; }, // 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 ); // jscs:ignore requireDotNotation } )( 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(); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === 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 length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; 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 } ); // JSHint would error on this code due to the Symbol not being defined in ES5. // Defining this global in .jshintrc would create a danger of using the global // unguarded in another place, it seems safer to just disable JSHint for these // three lines. /* jshint ignore: start */ if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = deletedIds[ Symbol.iterator ]; } /* jshint ignore: end */ // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: iOS 8.2 (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.2.1 * http://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2015-10-17 */ (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" + 1 * 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 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 as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[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 // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // 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 rwhitespace = new RegExp( whitespace + "+", "g" ), 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( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "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 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // 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 m, i, elem, nid, nidselect, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; while ( i-- ) { groups[i] = nidselect + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { 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 = arr.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 !== "undefined" && 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, parent, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( (parent = document.defaultView) && parent.top !== parent ) { // Support: IE 11 if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* 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( document.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // 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 !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); return m ? [ 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 !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too 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 !== "undefined" && 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( document.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 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<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("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // 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"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.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 self-exclusive // 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 === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( 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 === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( 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 document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !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 !== "undefined" && 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.replace( rwhitespace, " " ) + " " ).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, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; 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 // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && 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 ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // 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 ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ 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( 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 ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); 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, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator 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 ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( (oldCache = uniqueCache[ 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 uniqueCache[ 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( 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( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; 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 || outermost; } // Add elements passing elementMatchers directly to results // 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; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, 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 ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. 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 only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound 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, !context || 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-35+ // 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.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; 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 ) > -1 ) !== 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, // 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, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // init accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // 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 || root ).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 root.ready !== "undefined" ? root.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.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.uniqueSort( 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.uniqueSort( 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 dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( 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.uniqueSort( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; } ); var rnotwhite = ( /\S+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; 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" ? 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, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes 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.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = true; if ( !memory ) { self.disable(); } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } 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() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } 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() .progress( updateFunc( i, progressContexts, progressValues ) ) .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ); } 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; } // 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 ); window.removeEventListener( "load", completed ); } 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 || window.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. // Support: IE6-10 // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); // 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 window.setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } } )(); } } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownFirst = 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 !== "undefined" ) { // 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" ); // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch ( e ) { support.deleteExpando = false; } // Null elements to avoid leaks in IE. div = null; } )(); var 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 ( !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 ( !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, undefined } else { cache[ id ] = undefined; } } 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 ); } } ); ( 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 !== "undefined" ) { // 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 pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); 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 ); }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var 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 ) { 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 ); var rtagName = ( /<([\w:-]+)/ ); var rscriptType = ( /^$|\/(?:java|ecma)script/i ); var rleadingWhitespace = ( /^\s+/ ); var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|" + "details|dialog|figcaption|figure|footer|header|hgroup|main|" + "mark|meter|nav|output|picture|progress|section|summary|template|time|video"; function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } ( function() { var div = document.createElement( "div" ), fragment = document.createDocumentFragment(), input = document.createElement( "input" ); // 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 ); // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input = document.createElement( "input" ); input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // 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 // Cloned elements keep attachEvent handlers, we use addEventListener on IE9+ support.noCloneEvent = !!div.addEventListener; // Support: IE<9 // Since attributes and properties are the same in IE, // cleanData must set properties to undefined rather than use removeAttribute div[ jQuery.expando ] = 1; support.attributes = !div.getAttribute( jQuery.expando ); } )(); // We have to close these tags to support XHTML (#13200) var wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], // Support: IE8 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>" ] }; // Support: IE8-IE9 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 !== "undefined" ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== "undefined" ? 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; } // 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" ) ); } } var rhtml = /<|&#?\w+;/, rtbody = /<tbody/i; function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } function buildFragment( elems, context, scripts, selection, ignored ) { 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 ] + jQuery.htmlPrefilter( elem ) + 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++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } 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; } ( function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox (lack focus(in | out) events) for ( i in { submit: true, change: true, focusin: true } ) { eventName = "on" + i; if ( !( support[ i ] = eventName in window ) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i ] = 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|drag|drop)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE9 // See #13393 for more info function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // 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 ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } 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 elem; } 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 elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * 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 !== "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 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( "." ) > -1 ) { // 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.rnamespace = 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 && 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 ) && 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, j, ret, matched, handleObj, 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.rnamespace || event.rnamespace.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 i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Support (at least): Chrome, IE9 // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // // Support: Firefox<=42+ // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) if ( delegateCount && cur.nodeType && ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { /* 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 ) > -1 : 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: Safari 6-8+ // 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 detail 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; } } } }, // Piggyback on a donor event to simulate a different one simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true // Previously, `originalEvent: {}` was set here, so stopPropagation call // would not be triggered on donor event, since in our own // jQuery.event.stopPropagation function we had a check for existence of // originalEvent.stopPropagation method, so, consequently it would be a noop. // // Guard for simulated events was moved to jQuery.event.stopPropagation function // since `originalEvent` should point to the original event for the // constancy with other events and for more focused logic } ); jQuery.event.trigger( e, null, elem ); if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } } : 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.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 = { constructor: jQuery.Event, 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 || this.isSimulated ) { 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 // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://code.google.com/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). 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 mouseenter/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.submit ) { 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" ) ? // Support: IE <=8 // We use jQuery.prop instead of elem.form // to allow fixing the IE8 delegated submit issue (gh-2332) // by 3rd party polyfills/workarounds. jQuery.prop( elem, "form" ) : undefined; if ( form && !jQuery._data( form, "submit" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submitBubble = true; } ); jQuery._data( form, "submit", 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._submitBubble ) { delete event._submitBubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event ); } } }, 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.change ) { 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._justChanged = true; } } ); jQuery.event.add( this, "click._change", function( event ) { if ( this._justChanged && !event.isTrigger ) { this._justChanged = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event ); } ); } 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" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event ); } } ); jQuery._data( elem, "change", 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 ); } }; } // Support: Firefox // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome, Safari // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { 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 ) ); }; 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 ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); }, trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); var rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp( "<(?:" + nodeNames + ")[\\s/>]", "i" ), rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, // Support: IE 10-11, Edge 10240+ // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement( "div" ) ); // 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; } 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; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = collection.length, 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 collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { 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 ) { // Support: Android<4.1, PhantomJS<2 // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ 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 collection; } function remove( elem, selector, keepData ) { var node, elems = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = elems[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1></$2>" ); }, 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; }, cleanData: function( elems, /* internal */ forceAcceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, attributes = support.attributes, special = jQuery.event.special; for ( ; ( elem = elems[ i ] ) != null; i++ ) { if ( forceAcceptData || 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 ]; // Support: IE<9 // IE does not allow us to delete expando properties from nodes // IE creates expando attributes along with the property // IE does not have a removeAttribute function on Document nodes if ( !attributes && typeof elem.removeAttribute !== "undefined" ) { elem.removeAttribute( internalKey ); // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://code.google.com/p/chromium/issues/detail?id=378607 } else { elem[ internalKey ] = undefined; } deletedIds.push( id ); } } } } } } ); jQuery.fn.extend( { // Keep domManip exposed until 3.0 (gh-2225) domManip: domManip, detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, 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 domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, 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 domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, 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 = jQuery.htmlPrefilter( value ); 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 ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); 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 = { // Support: Firefox // We have to pre-define these values for FF (#10227) HTML: "block", BODY: "block" }; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), 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; } var rmargin = ( /^margin/ ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var 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 documentElement = document.documentElement; ( function() { var pixelPositionVal, pixelMarginRightVal, boxSizingReliableVal, reliableHiddenOffsetsVal, reliableMarginRightVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } div.style.cssText = "float:left;opacity:.5"; // Support: IE<9 // Make sure that element opacity exists (as opposed to filter) support.opacity = div.style.opacity === "0.5"; // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!div.style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container = document.createElement( "div" ); container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute"; div.innerHTML = ""; container.appendChild( div ); // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing support.boxSizing = div.style.boxSizing === "" || div.style.MozBoxSizing === "" || div.style.WebkitBoxSizing === ""; jQuery.extend( support, { reliableHiddenOffsets: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return reliableHiddenOffsetsVal; }, boxSizingReliable: function() { // We're checking for pixelPositionVal here instead of boxSizingReliableVal // since that compresses better and they're computed together anyway. if ( pixelPositionVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelMarginRight: function() { // Support: Android 4.0-4.3 if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelMarginRightVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, reliableMarginRight: function() { // Support: Android 2.3 if ( pixelPositionVal == null ) { computeStyleTests(); } return reliableMarginRightVal; }, reliableMarginLeft: function() { // Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37 if ( pixelPositionVal == null ) { computeStyleTests(); } return reliableMarginLeftVal; } } ); function computeStyleTests() { var contents, divStyle, documentElement = document.documentElement; // Setup documentElement.appendChild( container ); div.style.cssText = // Support: Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%"; // Support: IE<9 // Assume reasonable values in the absence of getComputedStyle pixelPositionVal = boxSizingReliableVal = reliableMarginLeftVal = false; pixelMarginRightVal = reliableMarginRightVal = true; // Check for getComputedStyle so that this code is not run in IE<9. if ( window.getComputedStyle ) { divStyle = window.getComputedStyle( div ); pixelPositionVal = ( divStyle || {} ).top !== "1%"; reliableMarginLeftVal = ( divStyle || {} ).marginLeft === "2px"; boxSizingReliableVal = ( divStyle || { width: "4px" } ).width === "4px"; // Support: Android 4.0 - 4.3 only // Some styles come back with percentage values, even though they shouldn't div.style.marginRight = "50%"; pixelMarginRightVal = ( divStyle || { marginRight: "4px" } ).marginRight === "4px"; // Support: Android 2.3 only // 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: 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 ) || {} ).marginRight ); div.removeChild( contents ); } // Support: IE6-8 // First check that getClientRects works as expected // 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.style.display = "none"; reliableHiddenOffsetsVal = div.getClientRects().length === 0; if ( reliableHiddenOffsetsVal ) { div.style.display = ""; 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; } } // Teardown documentElement.removeChild( container ); } } )(); var getStyles, curCSS, rposition = /^(top|right|bottom|left)$/; if ( window.getComputedStyle ) { getStyles = function( elem ) { // Support: IE<=11+, Firefox<=30+ (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; 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; // Support: Opera 12.1x only // Fall back to style even without computed // computed is undefined for elems on document fragments if ( ( ret === "" || ret === undefined ) && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } if ( computed ) { // 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 ( !support.pixelMarginRight() && 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 ( 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() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/i, // 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" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( name ) { // shortcut for names that are not vendor prefixed if ( name in emptyStyle ) { return name; } // check for vendor prefixed names var capName = name.charAt( 0 ).toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } 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"; // Support: IE11 only // In IE 11 fullscreen elements inside of an iframe have // 100x too small dimensions (gh-1764). if ( document.msFullscreenElement && window.top !== window ) { // Support: IE11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. if ( elem.getClientRects().length ) { val = Math.round( elem.getBoundingClientRect()[ name ] * 100 ); } } // 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: { "animationIterationCount": true, "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( origName ) || 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 "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // 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 the unit (except for certain CSS properties) if ( type === "number" ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "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( origName ) || 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 || isFinite( 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 ? 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 ) { return swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || // Support: IE<=11+ // Running getBoundingClientRect on a disconnected node in IE throws an error // Support: IE8 only // getClientRects() errors on disconnected elems ( jQuery.contains( elem.ownerDocument, elem ) ? elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) : 0 ) ) + "px"; } } ); // 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 || jQuery.easing._default; 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; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && 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.nodeType === 1 && ( 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; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; // Animations created synchronously will run synchronously function createFxNow() { window.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 = ( Animation.tweeners[ prop ] || [] ).concat( Animation.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 = Animation.prefilters.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 ), // Support: Android 2.3 // 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: {}, easing: jQuery.easing._default }, 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.notifyWith( elem, [ animation, 1, 0 ] ); 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 = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( jQuery.isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = jQuery.proxy( result.stop, 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, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnotwhite ); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.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 = window.setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { window.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://web.archive.org/web/20100324014747/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 = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var a, input = document.createElement( "input" ), div = document.createElement( "div" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); // 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 ]; // Support: Windows Web Apps (WWA) // `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "checkbox" ); div.appendChild( input ); a = div.getElementsByTagName( "a" )[ 0 ]; // First batch of tests. 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, rspaces = /[\x20\t\r\n\f]+/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) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " ); } }, 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 ) > -1 ) { // 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 ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { 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 ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { 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 ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, 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 IE8-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; } } } }, 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 ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); } else { // Support: IE<9 // Use defaultChecked and defaultSelected for oldIE elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { attrHandle[ 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; }; } else { attrHandle[ name ] = 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 sensitivity 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( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // 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; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } 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/ // 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; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // 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+ // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup 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; }, set: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } 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; function getClass( elem ) { return jQuery.attr( elem, "class" ) || ""; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + curValue + " " ).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 ( curValue !== finalValue ) { jQuery.attr( elem, "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { jQuery.attr( elem, "class", 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, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( type === "string" ) { // Toggle individual class names 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 ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // store className if set jQuery._data( this, "__className__", 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. jQuery.attr( this, "class", className || value === false ? "" : jQuery._data( this, "__className__" ) || "" ); } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + getClass( elem ) + " " ).replace( rclass, " " ) .indexOf( className ) > -1 ) { 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 ); } } ); var location = window.location; 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 window.DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } else { // IE xml = new window.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 rhash = /#.*$/, rts = /([?&])_=[^&]*/, // IE leaves an \r character at EOL rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // #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( "*" ), // Document location ajaxLocation = location.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" ] ) { // jscs:ignore requireDotNotation 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: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, 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 // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && 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 ] ); } // If request was aborted inside ajaxSend, stop there if ( state === 2 ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.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 ) { window.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; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery._evalUrl = function( url ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", cache: true, 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(); } } ); function getDisplay( elem ) { return elem.style && elem.style.display || jQuery.css( elem, "display" ); } function filterHidden( elem ) { while ( elem && elem.nodeType === 1 ) { if ( getDisplay( elem ) === "none" || elem.type === "hidden" ) { return true; } elem = elem.parentNode; } return false; } jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return support.reliableHiddenOffsets() ? ( elem.offsetWidth <= 0 && elem.offsetHeight <= 0 && !elem.getClientRects().length ) : filterHidden( elem ); }; 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" && v != null ? 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-IE8 function() { // XHR cannot access local files, always use ActiveX for that case if ( this.isLocal ) { return createActiveXHR(); } // Support: IE 9-11 // IE seems to error on cross-domain PATCH requests when ActiveX XHR // is used. In IE 9+ always use the native XHR. // Note: this condition won't catch Edge as it doesn't define // document.documentMode but it also doesn't support ActiveX so it won't // reach this code. if ( document.documentMode > 8 ) { return createStandardXHR(); } // Support: IE<9 // 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" return /^(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) // See https://support.microsoft.com/kb/2856746 for more info if ( window.attachEvent ) { window.attachEvent( "onunload", 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() ); } }; // Do send the request // `xhr.send` may raise an exception, but it will be // handled in jQuery.ajax (so no try/catch here) 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 window.setTimeout( callback ); } else { // Register the callback, but delay it in case `xhr.send` throws // 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: /\b(?:java|ecma)script\b/ }, 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" ) === 0 && 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() { // If previous value didn't exist - remove it if ( overwritten === undefined ) { jQuery( window ).removeProp( callbackName ); // Otherwise restore preexisting value } else { 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 = 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, type, response, self = this, off = url.indexOf( " " ); if ( off > -1 ) { 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. // Make value of this field explicit since // user can override it through ajaxSetup method type: type || "GET", 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 ); // If the request succeeds, this function gets "data", "status", "jqXHR" // but they are ignored because response was set above. // If it fails, this function gets "jqXHR", "status", "error" } ).always( callback && function( jqXHR, status ) { self.each( function() { callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] ); } ); } ); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; } ); jQuery.expr.filters.animated = function( elem ) { return jQuery.grep( jQuery.timers, function( fn ) { return elem === fn.elem; } ).length; }; /** * 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 ) ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, 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 !== "undefined" ) { 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; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return 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 ); }; } ); // Support: Safari<7-8+, Chrome<37-44+ // 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 ); }; } ); } ); jQuery.fn.extend( { 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 ); } } ); // 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 ( !noGlobal ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
ajax/libs/inferno/1.0.3/inferno-compat.js
Amomo/cdnjs
/*! * inferno-compat v1.0.3 * (c) 2016 Dominic Gannaway * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('proptypes'), require('./inferno-component'), require('./inferno')) : typeof define === 'function' && define.amd ? define(['exports', 'proptypes', 'inferno-component', 'inferno'], factory) : (factory((global.Inferno = global.Inferno || {}),global.PropTypes,global.Inferno.Component,global.Inferno)); }(this, (function (exports,PropTypes,Component,inferno) { 'use strict'; PropTypes = 'default' in PropTypes ? PropTypes['default'] : PropTypes; Component = 'default' in Component ? Component['default'] : Component; // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though function isStatefulComponent(o) { return !isUndefined(o.prototype) && !isUndefined(o.prototype.render); } function isNullOrUndef$1(obj) { return isUndefined(obj) || isNull(obj); } function isInvalid(obj) { return isNull(obj) || obj === false || isTrue(obj) || isUndefined(obj); } function isFunction(obj) { return typeof obj === 'function'; } function isAttrAnEvent(attr) { return attr[0] === 'o' && attr[1] === 'n' && attr.length > 3; } function isString(obj) { return typeof obj === 'string'; } function isNull(obj) { return obj === null; } function isTrue(obj) { return obj === true; } function isUndefined(obj) { return obj === undefined; } function isObject(o) { return typeof o === 'object'; } function isValidElement(obj) { var isNotANullObject = isObject(obj) && isNull(obj) === false; if (isNotANullObject === false) { return false; } var flags = obj.flags; return !!(flags & (28 /* Component */ | 3970 /* Element */)); } // don't autobind these methods since they already have guaranteed context. var AUTOBIND_BLACKLIST = { constructor: 1, render: 1, shouldComponentUpdate: 1, componentWillReceiveProps: 1, componentWillUpdate: 1, componentDidUpdate: 1, componentWillMount: 1, componentDidMount: 1, componentWillUnmount: 1, componentDidUnmount: 1 }; function extend(base, props, all) { for (var key in props) { if (all === true || !isNullOrUndef$1(props[key])) { base[key] = props[key]; } } return base; } function bindAll(ctx) { for (var i in ctx) { var v = ctx[i]; if (typeof v === 'function' && !v.__bound && !AUTOBIND_BLACKLIST[i]) { (ctx[i] = v.bind(ctx)).__bound = true; } } } function collateMixins(mixins, keyed) { if ( keyed === void 0 ) keyed = {}; for (var i = 0; i < mixins.length; i++) { var mixin = mixins[i]; // Surprise: Mixins can have mixins if (mixin.mixins) { // Recursively collate sub-mixins collateMixins(mixin.mixins, keyed); } for (var key in mixin) { if (mixin.hasOwnProperty(key) && typeof mixin[key] === 'function') { (keyed[key] || (keyed[key] = [])).push(mixin[key]); } } } return keyed; } function applyMixin(key, inst, mixin) { var original = inst[key]; inst[key] = function () { var arguments$1 = arguments; var ret; for (var i = 0; i < mixin.length; i++) { var method = mixin[i]; var _ret = method.apply(inst, arguments$1); if (!isUndefined(_ret)) { ret = _ret; } } if (original) { var _ret$1 = original.call(inst); if (!isUndefined(_ret$1)) { ret = _ret$1; } } return ret; }; } function applyMixins(inst, mixins) { for (var key in mixins) { if (mixins.hasOwnProperty(key)) { var mixin = mixins[key]; if (isFunction(mixin[0])) { applyMixin(key, inst, mixin); } else { inst[key] = mixin; } } } } function createClass(obj) { var Cl = (function (Component$$1) { function Cl(props) { Component$$1.call(this, props); this.isMounted = function () { return !this._unmounted; }; extend(this, obj); if (Cl.mixins) { applyMixins(this, Cl.mixins); } bindAll(this); if (obj.getInitialState) { this.state = obj.getInitialState.call(this); } } if ( Component$$1 ) Cl.__proto__ = Component$$1; Cl.prototype = Object.create( Component$$1 && Component$$1.prototype ); Cl.prototype.constructor = Cl; return Cl; }(Component)); Cl.displayName = obj.displayName || 'Component'; Cl.propTypes = obj.propTypes; Cl.defaultProps = obj.getDefaultProps ? obj.getDefaultProps() : undefined; Cl.mixins = obj.mixins && collateMixins(obj.mixins); if (obj.statics) { extend(Cl, obj.statics); } return Cl; } var componentHooks = { onComponentWillMount: true, onComponentDidMount: true, onComponentWillUnmount: true, onComponentShouldUpdate: true, onComponentWillUpdate: true, onComponentDidUpdate: true }; function createElement$1(name, props) { var _children = [], len = arguments.length - 2; while ( len-- > 0 ) _children[ len ] = arguments[ len + 2 ]; if (isInvalid(name) || isObject(name)) { throw new Error('Inferno Error: createElement() name parameter cannot be undefined, null, false or true, It must be a string, class or function.'); } var children = _children; var ref = null; var key = null; var events = null; var flags = 0; if (_children) { if (_children.length === 1) { children = _children[0]; } else if (_children.length === 0) { children = undefined; } } if (isString(name)) { flags = 2 /* HtmlElement */; switch (name) { case 'svg': flags = 128 /* SvgElement */; break; case 'input': flags = 512 /* InputElement */; break; case 'textarea': flags = 1024 /* TextareaElement */; break; case 'select': flags = 2048 /* SelectElement */; break; default: } for (var prop in props) { if (prop === 'key') { key = props.key; delete props.key; } else if (prop === 'children' && isUndefined(children)) { children = props.children; // always favour children args, default to props } else if (prop === 'ref') { ref = props.ref; } else if (isAttrAnEvent(prop)) { if (!events) { events = {}; } events[prop] = props[prop]; delete props[prop]; } } } else { flags = isStatefulComponent(name) ? 4 /* ComponentClass */ : 8 /* ComponentFunction */; if (!isUndefined(children)) { if (!props) { props = {}; } props.children = children; children = null; } for (var prop$1 in props) { if (componentHooks[prop$1]) { if (!ref) { ref = {}; } ref[prop$1] = props[prop$1]; } else if (prop$1 === 'key') { key = props.key; delete props.key; } } } return inferno.createVNode(flags, name, props, children, events, key, ref); } inferno.options.findDOMNodeEnabled = true; function unmountComponentAtNode(container) { inferno.render(null, container); return true; } function isNullOrUndef(children) { return children === null || children === undefined; } var ARR = []; var Children = { map: function map(children, fn, ctx) { if (isNullOrUndef(children)) {return children;} children = Children.toArray(children); if (ctx && ctx !== children) {fn = fn.bind(ctx);} return children.map(fn); }, forEach: function forEach(children, fn, ctx) { if (isNullOrUndef(children)) {return children;} children = Children.toArray(children); if (ctx && ctx !== children) {fn = fn.bind(ctx);} children.forEach(fn); }, count: function count(children) { children = Children.toArray(children); return children.length; }, only: function only(children) { children = Children.toArray(children); if (children.length !== 1) {throw new Error('Children.only() expects only one child.');} return children[0]; }, toArray: function toArray(children) { if (isNullOrUndef(children)) {return [];} return Array.isArray && Array.isArray(children) ? children : ARR.concat(children); } }; var currentComponent = null; Component.prototype.isReactComponent = {}; inferno.options.beforeRender = function (component) { currentComponent = component; }; inferno.options.afterRender = function () { currentComponent = null; }; var version = '15.4.1'; function normalizeProps(name, props) { if ((name === 'input' || name === 'textarea') && props.onChange) { var eventName = props.type === 'checkbox' ? 'onclick' : 'oninput'; if (!props[eventName]) { props[eventName] = props.onChange; delete props.onChange; } } } // we need to add persist() to Event (as React has it for synthetic events) // this is a hack and we really shouldn't be modifying a global object this way, // but there isn't a performant way of doing this apart from trying to proxy // every prop event that starts with "on", i.e. onClick or onKeyPress // but in reality devs use onSomething for many things, not only for // input events if (typeof Event !== 'undefined' && !Event.prototype.persist) { Event.prototype.persist = function () {}; } var injectStringRefs = function (originalFunction) { return function (name, _props) { var children = [], len = arguments.length - 2; while ( len-- > 0 ) children[ len ] = arguments[ len + 2 ]; var props = _props || {}; var ref = props.ref; if (typeof ref === 'string') { props.ref = function (val) { if (this && this.refs) { this.refs[ref] = val; } }.bind(currentComponent || null); } if (typeof name === 'string') { normalizeProps(name, props); } return originalFunction.apply(void 0, [ name, props ].concat( children )); }; }; var createElement = injectStringRefs(createElement$1); var cloneElement = injectStringRefs(inferno.cloneVNode); var oldCreateVNode = inferno.options.createVNode; inferno.options.createVNode = function (vNode) { var children = vNode.children; var props = vNode.props; if (isNullOrUndef(vNode.props)) { props = vNode.props = {}; } if (!isNullOrUndef(children) && isNullOrUndef(props.children)) { props.children = children; } if (oldCreateVNode) { oldCreateVNode(vNode); } }; // Credit: preact-compat - https://github.com/developit/preact-compat :) function shallowDiffers(a, b) { for (var i in a) {if (!(i in b)) {return true;}} for (var i$1 in b) {if (a[i$1] !== b[i$1]) {return true;}} return false; } function PureComponent(props, context) { Component.call(this, props, context); } PureComponent.prototype = new Component({}, {}); PureComponent.prototype.shouldComponentUpdate = function (props, state) { return shallowDiffers(this.props, props) || shallowDiffers(this.state, state); }; var WrapperComponent = (function (Component$$1) { function WrapperComponent () { Component$$1.apply(this, arguments); } if ( Component$$1 ) WrapperComponent.__proto__ = Component$$1; WrapperComponent.prototype = Object.create( Component$$1 && Component$$1.prototype ); WrapperComponent.prototype.constructor = WrapperComponent; WrapperComponent.prototype.getChildContext = function getChildContext () { return this.props.context; }; WrapperComponent.prototype.render = function render (props) { return props.children; }; return WrapperComponent; }(Component)); function unstable_renderSubtreeIntoContainer(parentComponent, vNode, container, callback) { var wrapperVNode = inferno.createVNode(4, WrapperComponent, { context: parentComponent.context, children: vNode }); var component = inferno.render(wrapperVNode, container); if (callback) { callback(component); } return component; } var index = { createVNode: inferno.createVNode, render: inferno.render, isValidElement: isValidElement, createElement: createElement, Component: Component, PureComponent: PureComponent, unmountComponentAtNode: unmountComponentAtNode, cloneElement: cloneElement, PropTypes: PropTypes, createClass: createClass, findDOMNode: inferno.findDOMNode, Children: Children, cloneVNode: inferno.cloneVNode, NO_OP: inferno.NO_OP, version: version, unstable_renderSubtreeIntoContainer: unstable_renderSubtreeIntoContainer }; exports.createVNode = inferno.createVNode; exports.render = inferno.render; exports.isValidElement = isValidElement; exports.createElement = createElement; exports.Component = Component; exports.PureComponent = PureComponent; exports.unmountComponentAtNode = unmountComponentAtNode; exports.cloneElement = cloneElement; exports.PropTypes = PropTypes; exports.createClass = createClass; exports.findDOMNode = inferno.findDOMNode; exports.Children = Children; exports.cloneVNode = inferno.cloneVNode; exports.NO_OP = inferno.NO_OP; exports.version = version; exports.unstable_renderSubtreeIntoContainer = unstable_renderSubtreeIntoContainer; exports['default'] = index; Object.defineProperty(exports, '__esModule', { value: true }); })));
ajax/libs/oojs-ui/0.19.3/oojs-ui.js
sufuf3/cdnjs
/*! * OOjs UI v0.19.3-pre (72b81a54a7) * https://www.mediawiki.org/wiki/OOjs_UI * * Copyright 2011–2017 OOjs UI Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2017-02-21T22:25:51Z */ ( function ( OO ) { 'use strict'; /** * Namespace for all classes, static methods and static properties. * * @class * @singleton */ OO.ui = {}; OO.ui.bind = $.proxy; /** * @property {Object} */ OO.ui.Keys = { UNDEFINED: 0, BACKSPACE: 8, DELETE: 46, LEFT: 37, RIGHT: 39, UP: 38, DOWN: 40, ENTER: 13, END: 35, HOME: 36, TAB: 9, PAGEUP: 33, PAGEDOWN: 34, ESCAPE: 27, SHIFT: 16, SPACE: 32 }; /** * Constants for MouseEvent.which * * @property {Object} */ OO.ui.MouseButtons = { LEFT: 1, MIDDLE: 2, RIGHT: 3 }; /** * @property {number} * @private */ OO.ui.elementId = 0; /** * Generate a unique ID for element * * @return {string} ID */ OO.ui.generateElementId = function () { OO.ui.elementId++; return 'oojsui-' + OO.ui.elementId; }; /** * Check if an element is focusable. * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14 * * @param {jQuery} $element Element to test * @return {boolean} */ OO.ui.isFocusableElement = function ( $element ) { var nodeName, element = $element[ 0 ]; // Anything disabled is not focusable if ( element.disabled ) { return false; } // Check if the element is visible if ( !( // This is quicker than calling $element.is( ':visible' ) $.expr.filters.visible( element ) && // Check that all parents are visible !$element.parents().addBack().filter( function () { return $.css( this, 'visibility' ) === 'hidden'; } ).length ) ) { return false; } // Check if the element is ContentEditable, which is the string 'true' if ( element.contentEditable === 'true' ) { return true; } // Anything with a non-negative numeric tabIndex is focusable. // Use .prop to avoid browser bugs if ( $element.prop( 'tabIndex' ) >= 0 ) { return true; } // Some element types are naturally focusable // (indexOf is much faster than regex in Chrome and about the // same in FF: https://jsperf.com/regex-vs-indexof-array2) nodeName = element.nodeName.toLowerCase(); if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) { return true; } // Links and areas are focusable if they have an href if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) { return true; } return false; }; /** * Find a focusable child * * @param {jQuery} $container Container to search in * @param {boolean} [backwards] Search backwards * @return {jQuery} Focusable child, an empty jQuery object if none found */ OO.ui.findFocusable = function ( $container, backwards ) { var $focusable = $( [] ), // $focusableCandidates is a superset of things that // could get matched by isFocusableElement $focusableCandidates = $container .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' ); if ( backwards ) { $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates ); } $focusableCandidates.each( function () { var $this = $( this ); if ( OO.ui.isFocusableElement( $this ) ) { $focusable = $this; return false; } } ); return $focusable; }; /** * Get the user's language and any fallback languages. * * These language codes are used to localize user interface elements in the user's language. * * In environments that provide a localization system, this function should be overridden to * return the user's language(s). The default implementation returns English (en) only. * * @return {string[]} Language codes, in descending order of priority */ OO.ui.getUserLanguages = function () { return [ 'en' ]; }; /** * Get a value in an object keyed by language code. * * @param {Object.<string,Mixed>} obj Object keyed by language code * @param {string|null} [lang] Language code, if omitted or null defaults to any user language * @param {string} [fallback] Fallback code, used if no matching language can be found * @return {Mixed} Local value */ OO.ui.getLocalValue = function ( obj, lang, fallback ) { var i, len, langs; // Requested language if ( obj[ lang ] ) { return obj[ lang ]; } // Known user language langs = OO.ui.getUserLanguages(); for ( i = 0, len = langs.length; i < len; i++ ) { lang = langs[ i ]; if ( obj[ lang ] ) { return obj[ lang ]; } } // Fallback language if ( obj[ fallback ] ) { return obj[ fallback ]; } // First existing language for ( lang in obj ) { return obj[ lang ]; } return undefined; }; /** * Check if a node is contained within another node * * Similar to jQuery#contains except a list of containers can be supplied * and a boolean argument allows you to include the container in the match list * * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in * @param {HTMLElement} contained Node to find * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants * @return {boolean} The node is in the list of target nodes */ OO.ui.contains = function ( containers, contained, matchContainers ) { var i; if ( !Array.isArray( containers ) ) { containers = [ containers ]; } for ( i = containers.length - 1; i >= 0; i-- ) { if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) { return true; } } return false; }; /** * Return a function, that, as long as it continues to be invoked, will not * be triggered. The function will be called after it stops being called for * N milliseconds. If `immediate` is passed, trigger the function on the * leading edge, instead of the trailing. * * Ported from: http://underscorejs.org/underscore.js * * @param {Function} func * @param {number} wait * @param {boolean} immediate * @return {Function} */ OO.ui.debounce = function ( func, wait, immediate ) { var timeout; return function () { var context = this, args = arguments, later = function () { timeout = null; if ( !immediate ) { func.apply( context, args ); } }; if ( immediate && !timeout ) { func.apply( context, args ); } if ( !timeout || wait ) { clearTimeout( timeout ); timeout = setTimeout( later, wait ); } }; }; /** * Puts a console warning with provided message. * * @param {string} message */ OO.ui.warnDeprecation = function ( message ) { if ( OO.getProp( window, 'console', 'warn' ) !== undefined ) { // eslint-disable-next-line no-console console.warn( message ); } }; /** * Returns a function, that, when invoked, will only be triggered at most once * during a given window of time. If called again during that window, it will * wait until the window ends and then trigger itself again. * * As it's not knowable to the caller whether the function will actually run * when the wrapper is called, return values from the function are entirely * discarded. * * @param {Function} func * @param {number} wait * @return {Function} */ OO.ui.throttle = function ( func, wait ) { var context, args, timeout, previous = 0, run = function () { timeout = null; previous = OO.ui.now(); func.apply( context, args ); }; return function () { // Check how long it's been since the last time the function was // called, and whether it's more or less than the requested throttle // period. If it's less, run the function immediately. If it's more, // set a timeout for the remaining time -- but don't replace an // existing timeout, since that'd indefinitely prolong the wait. var remaining = wait - ( OO.ui.now() - previous ); context = this; args = arguments; if ( remaining <= 0 ) { // Note: unless wait was ridiculously large, this means we'll // automatically run the first time the function was called in a // given period. (If you provide a wait period larger than the // current Unix timestamp, you *deserve* unexpected behavior.) clearTimeout( timeout ); run(); } else if ( !timeout ) { timeout = setTimeout( run, remaining ); } }; }; /** * A (possibly faster) way to get the current timestamp as an integer * * @return {number} Current timestamp */ OO.ui.now = Date.now || function () { return new Date().getTime(); }; /** * Reconstitute a JavaScript object corresponding to a widget created by * the PHP implementation. * * This is an alias for `OO.ui.Element.static.infuse()`. * * @param {string|HTMLElement|jQuery} idOrNode * A DOM id (if a string) or node for the widget to infuse. * @return {OO.ui.Element} * The `OO.ui.Element` corresponding to this (infusable) document node. */ OO.ui.infuse = function ( idOrNode ) { return OO.ui.Element.static.infuse( idOrNode ); }; ( function () { /** * Message store for the default implementation of OO.ui.msg * * Environments that provide a localization system should not use this, but should override * OO.ui.msg altogether. * * @private */ var messages = { // Tool tip for a button that moves items in a list down one place 'ooui-outline-control-move-down': 'Move item down', // Tool tip for a button that moves items in a list up one place 'ooui-outline-control-move-up': 'Move item up', // Tool tip for a button that removes items from a list 'ooui-outline-control-remove': 'Remove item', // Label for the toolbar group that contains a list of all other available tools 'ooui-toolbar-more': 'More', // Label for the fake tool that expands the full list of tools in a toolbar group 'ooui-toolgroup-expand': 'More', // Label for the fake tool that collapses the full list of tools in a toolbar group 'ooui-toolgroup-collapse': 'Fewer', // Default label for the accept button of a confirmation dialog 'ooui-dialog-message-accept': 'OK', // Default label for the reject button of a confirmation dialog 'ooui-dialog-message-reject': 'Cancel', // Title for process dialog error description 'ooui-dialog-process-error': 'Something went wrong', // Label for process dialog dismiss error button, visible when describing errors 'ooui-dialog-process-dismiss': 'Dismiss', // Label for process dialog retry action button, visible when describing only recoverable errors 'ooui-dialog-process-retry': 'Try again', // Label for process dialog retry action button, visible when describing only warnings 'ooui-dialog-process-continue': 'Continue', // Label for the file selection widget's select file button 'ooui-selectfile-button-select': 'Select a file', // Label for the file selection widget if file selection is not supported 'ooui-selectfile-not-supported': 'File selection is not supported', // Label for the file selection widget when no file is currently selected 'ooui-selectfile-placeholder': 'No file is selected', // Label for the file selection widget's drop target 'ooui-selectfile-dragdrop-placeholder': 'Drop file here' }; /** * Get a localized message. * * After the message key, message parameters may optionally be passed. In the default implementation, * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc. * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as * they support unnamed, ordered message parameters. * * In environments that provide a localization system, this function should be overridden to * return the message translated in the user's language. The default implementation always returns * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n) * follows. * * @example * var i, iLen, button, * messagePath = 'oojs-ui/dist/i18n/', * languages = [ $.i18n().locale, 'ur', 'en' ], * languageMap = {}; * * for ( i = 0, iLen = languages.length; i < iLen; i++ ) { * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json'; * } * * $.i18n().load( languageMap ).done( function() { * // Replace the built-in `msg` only once we've loaded the internationalization. * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as * // you put off creating any widgets until this promise is complete, no English * // will be displayed. * OO.ui.msg = $.i18n; * * // A button displaying "OK" in the default locale * button = new OO.ui.ButtonWidget( { * label: OO.ui.msg( 'ooui-dialog-message-accept' ), * icon: 'check' * } ); * $( 'body' ).append( button.$element ); * * // A button displaying "OK" in Urdu * $.i18n().locale = 'ur'; * button = new OO.ui.ButtonWidget( { * label: OO.ui.msg( 'ooui-dialog-message-accept' ), * icon: 'check' * } ); * $( 'body' ).append( button.$element ); * } ); * * @param {string} key Message key * @param {...Mixed} [params] Message parameters * @return {string} Translated message with parameters substituted */ OO.ui.msg = function ( key ) { var message = messages[ key ], params = Array.prototype.slice.call( arguments, 1 ); if ( typeof message === 'string' ) { // Perform $1 substitution message = message.replace( /\$(\d+)/g, function ( unused, n ) { var i = parseInt( n, 10 ); return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n; } ); } else { // Return placeholder if message not found message = '[' + key + ']'; } return message; }; }() ); /** * Package a message and arguments for deferred resolution. * * Use this when you are statically specifying a message and the message may not yet be present. * * @param {string} key Message key * @param {...Mixed} [params] Message parameters * @return {Function} Function that returns the resolved message when executed */ OO.ui.deferMsg = function () { var args = arguments; return function () { return OO.ui.msg.apply( OO.ui, args ); }; }; /** * Resolve a message. * * If the message is a function it will be executed, otherwise it will pass through directly. * * @param {Function|string} msg Deferred message, or message text * @return {string} Resolved message */ OO.ui.resolveMsg = function ( msg ) { if ( $.isFunction( msg ) ) { return msg(); } return msg; }; /** * @param {string} url * @return {boolean} */ OO.ui.isSafeUrl = function ( url ) { // Keep this function in sync with php/Tag.php var i, protocolWhitelist; function stringStartsWith( haystack, needle ) { return haystack.substr( 0, needle.length ) === needle; } protocolWhitelist = [ 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs', 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh', 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp' ]; if ( url === '' ) { return true; } for ( i = 0; i < protocolWhitelist.length; i++ ) { if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) { return true; } } // This matches '//' too if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) { return true; } if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) { return true; } return false; }; /** * Check if the user has a 'mobile' device. * * For our purposes this means the user is primarily using an * on-screen keyboard, touch input instead of a mouse and may * have a physically small display. * * It is left up to implementors to decide how to compute this * so the default implementation always returns false. * * @return {boolean} Use is on a mobile device */ OO.ui.isMobile = function () { return false; }; /*! * Mixin namespace. */ /** * Namespace for OOjs UI mixins. * * Mixins are named according to the type of object they are intended to * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget * is intended to be mixed in to an instance of OO.ui.Widget. * * @class * @singleton */ OO.ui.mixin = {}; /** * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events * connected to them and can't be interacted with. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2] * for an example. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample * @cfg {string} [id] The HTML id attribute used in the rendered tag. * @cfg {string} [text] Text to insert * @cfg {Array} [content] An array of content elements to append (after #text). * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML. * Instances of OO.ui.Element will have their $element appended. * @cfg {jQuery} [$content] Content elements to append (after #text). * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName. * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object). * Data can also be specified with the #setData method. */ OO.ui.Element = function OoUiElement( config ) { // Configuration initialization config = config || {}; // Properties this.$ = $; this.visible = true; this.data = config.data; this.$element = config.$element || $( document.createElement( this.getTagName() ) ); this.elementGroup = null; // Initialization if ( Array.isArray( config.classes ) ) { this.$element.addClass( config.classes.join( ' ' ) ); } if ( config.id ) { this.$element.attr( 'id', config.id ); } if ( config.text ) { this.$element.text( config.text ); } if ( config.content ) { // The `content` property treats plain strings as text; use an // HtmlSnippet to append HTML content. `OO.ui.Element`s get their // appropriate $element appended. this.$element.append( config.content.map( function ( v ) { if ( typeof v === 'string' ) { // Escape string so it is properly represented in HTML. return document.createTextNode( v ); } else if ( v instanceof OO.ui.HtmlSnippet ) { // Bypass escaping. return v.toString(); } else if ( v instanceof OO.ui.Element ) { return v.$element; } return v; } ) ); } if ( config.$content ) { // The `$content` property treats plain strings as HTML. this.$element.append( config.$content ); } }; /* Setup */ OO.initClass( OO.ui.Element ); /* Static Properties */ /** * The name of the HTML tag used by the element. * * The static value may be ignored if the #getTagName method is overridden. * * @static * @inheritable * @property {string} */ OO.ui.Element.static.tagName = 'div'; /* Static Methods */ /** * Reconstitute a JavaScript object corresponding to a widget created * by the PHP implementation. * * @param {string|HTMLElement|jQuery} idOrNode * A DOM id (if a string) or node for the widget to infuse. * @return {OO.ui.Element} * The `OO.ui.Element` corresponding to this (infusable) document node. * For `Tag` objects emitted on the HTML side (used occasionally for content) * the value returned is a newly-created Element wrapping around the existing * DOM node. */ OO.ui.Element.static.infuse = function ( idOrNode ) { var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false ); // Verify that the type matches up. // FIXME: uncomment after T89721 is fixed (see T90929) /* if ( !( obj instanceof this['class'] ) ) { throw new Error( 'Infusion type mismatch!' ); } */ return obj; }; /** * Implementation helper for `infuse`; skips the type check and has an * extra property so that only the top-level invocation touches the DOM. * * @private * @param {string|HTMLElement|jQuery} idOrNode * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved * when the top-level widget of this infusion is inserted into DOM, * replacing the original node; or false for top-level invocation. * @return {OO.ui.Element} */ OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) { // look for a cached result of a previous infusion. var id, $elem, data, cls, parts, parent, obj, top, state, infusedChildren; if ( typeof idOrNode === 'string' ) { id = idOrNode; $elem = $( document.getElementById( id ) ); } else { $elem = $( idOrNode ); id = $elem.attr( 'id' ); } if ( !$elem.length ) { throw new Error( 'Widget not found: ' + id ); } if ( $elem[ 0 ].oouiInfused ) { $elem = $elem[ 0 ].oouiInfused; } data = $elem.data( 'ooui-infused' ); if ( data ) { // cached! if ( data === true ) { throw new Error( 'Circular dependency! ' + id ); } if ( domPromise ) { // pick up dynamic state, like focus, value of form inputs, scroll position, etc. state = data.constructor.static.gatherPreInfuseState( $elem, data ); // restore dynamic state after the new element is re-inserted into DOM under infused parent domPromise.done( data.restorePreInfuseState.bind( data, state ) ); infusedChildren = $elem.data( 'ooui-infused-children' ); if ( infusedChildren && infusedChildren.length ) { infusedChildren.forEach( function ( data ) { var state = data.constructor.static.gatherPreInfuseState( $elem, data ); domPromise.done( data.restorePreInfuseState.bind( data, state ) ); } ); } } return data; } data = $elem.attr( 'data-ooui' ); if ( !data ) { throw new Error( 'No infusion data found: ' + id ); } try { data = $.parseJSON( data ); } catch ( _ ) { data = null; } if ( !( data && data._ ) ) { throw new Error( 'No valid infusion data found: ' + id ); } if ( data._ === 'Tag' ) { // Special case: this is a raw Tag; wrap existing node, don't rebuild. return new OO.ui.Element( { $element: $elem } ); } parts = data._.split( '.' ); cls = OO.getProp.apply( OO, [ window ].concat( parts ) ); if ( cls === undefined ) { // The PHP output might be old and not including the "OO.ui" prefix // TODO: Remove this back-compat after next major release cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) ); if ( cls === undefined ) { throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ ); } } // Verify that we're creating an OO.ui.Element instance parent = cls.parent; while ( parent !== undefined ) { if ( parent === OO.ui.Element ) { // Safe break; } parent = parent.parent; } if ( parent !== OO.ui.Element ) { throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ ); } if ( domPromise === false ) { top = $.Deferred(); domPromise = top.promise(); } $elem.data( 'ooui-infused', true ); // prevent loops data.id = id; // implicit infusedChildren = []; data = OO.copy( data, null, function deserialize( value ) { var infused; if ( OO.isPlainObject( value ) ) { if ( value.tag ) { infused = OO.ui.Element.static.unsafeInfuse( value.tag, domPromise ); infusedChildren.push( infused ); // Flatten the structure infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] ); infused.$element.removeData( 'ooui-infused-children' ); return infused; } if ( value.html !== undefined ) { return new OO.ui.HtmlSnippet( value.html ); } } } ); // allow widgets to reuse parts of the DOM data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data ); // pick up dynamic state, like focus, value of form inputs, scroll position, etc. state = cls.static.gatherPreInfuseState( $elem[ 0 ], data ); // rebuild widget // eslint-disable-next-line new-cap obj = new cls( data ); // now replace old DOM with this new DOM. if ( top ) { // An efficient constructor might be able to reuse the entire DOM tree of the original element, // so only mutate the DOM if we need to. if ( $elem[ 0 ] !== obj.$element[ 0 ] ) { $elem.replaceWith( obj.$element ); // This element is now gone from the DOM, but if anyone is holding a reference to it, // let's allow them to OO.ui.infuse() it and do what they expect (T105828). // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design. $elem[ 0 ].oouiInfused = obj.$element; } top.resolve(); } obj.$element.data( 'ooui-infused', obj ); obj.$element.data( 'ooui-infused-children', infusedChildren ); // set the 'data-ooui' attribute so we can identify infused widgets obj.$element.attr( 'data-ooui', '' ); // restore dynamic state after the new element is inserted into DOM domPromise.done( obj.restorePreInfuseState.bind( obj, state ) ); return obj; }; /** * Pick out parts of `node`'s DOM to be reused when infusing a widget. * * This method **must not** make any changes to the DOM, only find interesting pieces and add them * to `config` (which should then be returned). Actual DOM juggling should then be done by the * constructor, which will be given the enhanced config. * * @protected * @param {HTMLElement} node * @param {Object} config * @return {Object} */ OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) { return config; }; /** * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node * (and its children) that represent an Element of the same class and the given configuration, * generated by the PHP implementation. * * This method is called just before `node` is detached from the DOM. The return value of this * function will be passed to #restorePreInfuseState after the newly created widget's #$element * is inserted into DOM to replace `node`. * * @protected * @param {HTMLElement} node * @param {Object} config * @return {Object} */ OO.ui.Element.static.gatherPreInfuseState = function () { return {}; }; /** * Get a jQuery function within a specific document. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is * not in an iframe * @return {Function} Bound jQuery function */ OO.ui.Element.static.getJQuery = function ( context, $iframe ) { function wrapper( selector ) { return $( selector, wrapper.context ); } wrapper.context = this.getDocument( context ); if ( $iframe ) { wrapper.$iframe = $iframe; } return wrapper; }; /** * Get the document of an element. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for * @return {HTMLDocument|null} Document object */ OO.ui.Element.static.getDocument = function ( obj ) { // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) || // Empty jQuery selections might have a context obj.context || // HTMLElement obj.ownerDocument || // Window obj.document || // HTMLDocument ( obj.nodeType === 9 && obj ) || null; }; /** * Get the window of an element or document. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for * @return {Window} Window object */ OO.ui.Element.static.getWindow = function ( obj ) { var doc = this.getDocument( obj ); return doc.defaultView; }; /** * Get the direction of an element or document. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for * @return {string} Text direction, either 'ltr' or 'rtl' */ OO.ui.Element.static.getDir = function ( obj ) { var isDoc, isWin; if ( obj instanceof jQuery ) { obj = obj[ 0 ]; } isDoc = obj.nodeType === 9; isWin = obj.document !== undefined; if ( isDoc || isWin ) { if ( isWin ) { obj = obj.document; } obj = obj.body; } return $( obj ).css( 'direction' ); }; /** * Get the offset between two frames. * * TODO: Make this function not use recursion. * * @static * @param {Window} from Window of the child frame * @param {Window} [to=window] Window of the parent frame * @param {Object} [offset] Offset to start with, used internally * @return {Object} Offset object, containing left and top properties */ OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) { var i, len, frames, frame, rect; if ( !to ) { to = window; } if ( !offset ) { offset = { top: 0, left: 0 }; } if ( from.parent === from ) { return offset; } // Get iframe element frames = from.parent.document.getElementsByTagName( 'iframe' ); for ( i = 0, len = frames.length; i < len; i++ ) { if ( frames[ i ].contentWindow === from ) { frame = frames[ i ]; break; } } // Recursively accumulate offset values if ( frame ) { rect = frame.getBoundingClientRect(); offset.left += rect.left; offset.top += rect.top; if ( from !== to ) { this.getFrameOffset( from.parent, offset ); } } return offset; }; /** * Get the offset between two elements. * * The two elements may be in a different frame, but in that case the frame $element is in must * be contained in the frame $anchor is in. * * @static * @param {jQuery} $element Element whose position to get * @param {jQuery} $anchor Element to get $element's position relative to * @return {Object} Translated position coordinates, containing top and left properties */ OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) { var iframe, iframePos, pos = $element.offset(), anchorPos = $anchor.offset(), elementDocument = this.getDocument( $element ), anchorDocument = this.getDocument( $anchor ); // If $element isn't in the same document as $anchor, traverse up while ( elementDocument !== anchorDocument ) { iframe = elementDocument.defaultView.frameElement; if ( !iframe ) { throw new Error( '$element frame is not contained in $anchor frame' ); } iframePos = $( iframe ).offset(); pos.left += iframePos.left; pos.top += iframePos.top; elementDocument = iframe.ownerDocument; } pos.left -= anchorPos.left; pos.top -= anchorPos.top; return pos; }; /** * Get element border sizes. * * @static * @param {HTMLElement} el Element to measure * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties */ OO.ui.Element.static.getBorders = function ( el ) { var doc = el.ownerDocument, win = doc.defaultView, style = win.getComputedStyle( el, null ), $el = $( el ), top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0, left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0, bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0, right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0; return { top: top, left: left, bottom: bottom, right: right }; }; /** * Get dimensions of an element or window. * * @static * @param {HTMLElement|Window} el Element to measure * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties */ OO.ui.Element.static.getDimensions = function ( el ) { var $el, $win, doc = el.ownerDocument || el.document, win = doc.defaultView; if ( win === el || el === doc.documentElement ) { $win = $( win ); return { borders: { top: 0, left: 0, bottom: 0, right: 0 }, scroll: { top: $win.scrollTop(), left: $win.scrollLeft() }, scrollbar: { right: 0, bottom: 0 }, rect: { top: 0, left: 0, bottom: $win.innerHeight(), right: $win.innerWidth() } }; } else { $el = $( el ); return { borders: this.getBorders( el ), scroll: { top: $el.scrollTop(), left: $el.scrollLeft() }, scrollbar: { right: $el.innerWidth() - el.clientWidth, bottom: $el.innerHeight() - el.clientHeight }, rect: el.getBoundingClientRect() }; } }; /** * Get scrollable object parent * * documentElement can't be used to get or set the scrollTop * property on Blink. Changing and testing its value lets us * use 'body' or 'documentElement' based on what is working. * * https://code.google.com/p/chromium/issues/detail?id=303131 * * @static * @param {HTMLElement} el Element to find scrollable parent for * @return {HTMLElement} Scrollable parent */ OO.ui.Element.static.getRootScrollableElement = function ( el ) { var scrollTop, body; if ( OO.ui.scrollableElement === undefined ) { body = el.ownerDocument.body; scrollTop = body.scrollTop; body.scrollTop = 1; if ( body.scrollTop === 1 ) { body.scrollTop = scrollTop; OO.ui.scrollableElement = 'body'; } else { OO.ui.scrollableElement = 'documentElement'; } } return el.ownerDocument[ OO.ui.scrollableElement ]; }; /** * Get closest scrollable container. * * Traverses up until either a scrollable element or the root is reached, in which case the window * will be returned. * * @static * @param {HTMLElement} el Element to find scrollable container for * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either * @return {HTMLElement} Closest scrollable container */ OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) { var i, val, // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and // 'overflow-y' have different values, so we need to check the separate properties. props = [ 'overflow-x', 'overflow-y' ], $parent = $( el ).parent(); if ( dimension === 'x' || dimension === 'y' ) { props = [ 'overflow-' + dimension ]; } while ( $parent.length ) { if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) { return $parent[ 0 ]; } i = props.length; while ( i-- ) { val = $parent.css( props[ i ] ); // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be // scrolled in that direction, but they can actually be scrolled programatically. The user can // unintentionally perform a scroll in such case even if the application doesn't scroll // programatically, e.g. when jumping to an anchor, or when using built-in find functionality. // This could cause funny issues... if ( val === 'auto' || val === 'scroll' ) { return $parent[ 0 ]; } } $parent = $parent.parent(); } return this.getDocument( el ).body; }; /** * Scroll element into view. * * @static * @param {HTMLElement} el Element to scroll into view * @param {Object} [config] Configuration options * @param {string} [config.duration='fast'] jQuery animation duration value * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit * to scroll in both directions * @param {Function} [config.complete] Function to call when scrolling completes. * Deprecated since 0.15.4, use the return promise instead. * @return {jQuery.Promise} Promise which resolves when the scroll is complete */ OO.ui.Element.static.scrollIntoView = function ( el, config ) { var position, animations, callback, container, $container, elementDimensions, containerDimensions, $window, deferred = $.Deferred(); // Configuration initialization config = config || {}; animations = {}; callback = typeof config.complete === 'function' && config.complete; if ( callback ) { OO.ui.warnDeprecation( 'Element#scrollIntoView: The `complete` callback config option is deprecated. Use the return promise instead.' ); } container = this.getClosestScrollableContainer( el, config.direction ); $container = $( container ); elementDimensions = this.getDimensions( el ); containerDimensions = this.getDimensions( container ); $window = $( this.getWindow( el ) ); // Compute the element's position relative to the container if ( $container.is( 'html, body' ) ) { // If the scrollable container is the root, this is easy position = { top: elementDimensions.rect.top, bottom: $window.innerHeight() - elementDimensions.rect.bottom, left: elementDimensions.rect.left, right: $window.innerWidth() - elementDimensions.rect.right }; } else { // Otherwise, we have to subtract el's coordinates from container's coordinates position = { top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ), bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom, left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ), right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right }; } if ( !config.direction || config.direction === 'y' ) { if ( position.top < 0 ) { animations.scrollTop = containerDimensions.scroll.top + position.top; } else if ( position.top > 0 && position.bottom < 0 ) { animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom ); } } if ( !config.direction || config.direction === 'x' ) { if ( position.left < 0 ) { animations.scrollLeft = containerDimensions.scroll.left + position.left; } else if ( position.left > 0 && position.right < 0 ) { animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right ); } } if ( !$.isEmptyObject( animations ) ) { $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration ); $container.queue( function ( next ) { if ( callback ) { callback(); } deferred.resolve(); next(); } ); } else { if ( callback ) { callback(); } deferred.resolve(); } return deferred.promise(); }; /** * Force the browser to reconsider whether it really needs to render scrollbars inside the element * and reserve space for them, because it probably doesn't. * * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow, * and then reattach (or show) them back. * * @static * @param {HTMLElement} el Element to reconsider the scrollbars on */ OO.ui.Element.static.reconsiderScrollbars = function ( el ) { var i, len, scrollLeft, scrollTop, nodes = []; // Save scroll position scrollLeft = el.scrollLeft; scrollTop = el.scrollTop; // Detach all children while ( el.firstChild ) { nodes.push( el.firstChild ); el.removeChild( el.firstChild ); } // Force reflow void el.offsetHeight; // Reattach all children for ( i = 0, len = nodes.length; i < len; i++ ) { el.appendChild( nodes[ i ] ); } // Restore scroll position (no-op if scrollbars disappeared) el.scrollLeft = scrollLeft; el.scrollTop = scrollTop; }; /* Methods */ /** * Toggle visibility of an element. * * @param {boolean} [show] Make element visible, omit to toggle visibility * @fires visible * @chainable */ OO.ui.Element.prototype.toggle = function ( show ) { show = show === undefined ? !this.visible : !!show; if ( show !== this.isVisible() ) { this.visible = show; this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible ); this.emit( 'toggle', show ); } return this; }; /** * Check if element is visible. * * @return {boolean} element is visible */ OO.ui.Element.prototype.isVisible = function () { return this.visible; }; /** * Get element data. * * @return {Mixed} Element data */ OO.ui.Element.prototype.getData = function () { return this.data; }; /** * Set element data. * * @param {Mixed} data Element data * @chainable */ OO.ui.Element.prototype.setData = function ( data ) { this.data = data; return this; }; /** * Check if element supports one or more methods. * * @param {string|string[]} methods Method or list of methods to check * @return {boolean} All methods are supported */ OO.ui.Element.prototype.supports = function ( methods ) { var i, len, support = 0; methods = Array.isArray( methods ) ? methods : [ methods ]; for ( i = 0, len = methods.length; i < len; i++ ) { if ( $.isFunction( this[ methods[ i ] ] ) ) { support++; } } return methods.length === support; }; /** * Update the theme-provided classes. * * @localdoc This is called in element mixins and widget classes any time state changes. * Updating is debounced, minimizing overhead of changing multiple attributes and * guaranteeing that theme updates do not occur within an element's constructor */ OO.ui.Element.prototype.updateThemeClasses = function () { OO.ui.theme.queueUpdateElementClasses( this ); }; /** * Get the HTML tag name. * * Override this method to base the result on instance information. * * @return {string} HTML tag name */ OO.ui.Element.prototype.getTagName = function () { return this.constructor.static.tagName; }; /** * Check if the element is attached to the DOM * * @return {boolean} The element is attached to the DOM */ OO.ui.Element.prototype.isElementAttached = function () { return $.contains( this.getElementDocument(), this.$element[ 0 ] ); }; /** * Get the DOM document. * * @return {HTMLDocument} Document object */ OO.ui.Element.prototype.getElementDocument = function () { // Don't cache this in other ways either because subclasses could can change this.$element return OO.ui.Element.static.getDocument( this.$element ); }; /** * Get the DOM window. * * @return {Window} Window object */ OO.ui.Element.prototype.getElementWindow = function () { return OO.ui.Element.static.getWindow( this.$element ); }; /** * Get closest scrollable container. * * @return {HTMLElement} Closest scrollable container */ OO.ui.Element.prototype.getClosestScrollableElementContainer = function () { return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] ); }; /** * Get group element is in. * * @return {OO.ui.mixin.GroupElement|null} Group element, null if none */ OO.ui.Element.prototype.getElementGroup = function () { return this.elementGroup; }; /** * Set group element is in. * * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none * @chainable */ OO.ui.Element.prototype.setElementGroup = function ( group ) { this.elementGroup = group; return this; }; /** * Scroll element into view. * * @param {Object} [config] Configuration options * @return {jQuery.Promise} Promise which resolves when the scroll is complete */ OO.ui.Element.prototype.scrollElementIntoView = function ( config ) { if ( !this.isElementAttached() || !this.isVisible() || ( this.getElementGroup() && !this.getElementGroup().isVisible() ) ) { return $.Deferred().resolve(); } return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config ); }; /** * Restore the pre-infusion dynamic state for this widget. * * This method is called after #$element has been inserted into DOM. The parameter is the return * value of #gatherPreInfuseState. * * @protected * @param {Object} state */ OO.ui.Element.prototype.restorePreInfuseState = function () { }; /** * Wraps an HTML snippet for use with configuration values which default * to strings. This bypasses the default html-escaping done to string * values. * * @class * * @constructor * @param {string} [content] HTML content */ OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) { // Properties this.content = content; }; /* Setup */ OO.initClass( OO.ui.HtmlSnippet ); /* Methods */ /** * Render into HTML. * * @return {string} Unchanged HTML snippet. */ OO.ui.HtmlSnippet.prototype.toString = function () { return this.content; }; /** * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined. * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout}, * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout}, * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples. * * @abstract * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options */ OO.ui.Layout = function OoUiLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.Layout.parent.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Initialization this.$element.addClass( 'oo-ui-layout' ); }; /* Setup */ OO.inheritClass( OO.ui.Layout, OO.ui.Element ); OO.mixinClass( OO.ui.Layout, OO.EventEmitter ); /** * Widgets are compositions of one or more OOjs UI elements that users can both view * and interact with. All widgets can be configured and modified via a standard API, * and their state can change dynamically according to a model. * * @abstract * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their * appearance reflects this state. */ OO.ui.Widget = function OoUiWidget( config ) { // Initialize config config = $.extend( { disabled: false }, config ); // Parent constructor OO.ui.Widget.parent.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.disabled = null; this.wasDisabled = null; // Initialization this.$element.addClass( 'oo-ui-widget' ); this.setDisabled( !!config.disabled ); }; /* Setup */ OO.inheritClass( OO.ui.Widget, OO.ui.Element ); OO.mixinClass( OO.ui.Widget, OO.EventEmitter ); /* Static Properties */ /** * Whether this widget will behave reasonably when wrapped in an HTML `<label>`. If this is true, * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click * handling. * * @static * @inheritable * @property {boolean} */ OO.ui.Widget.static.supportsSimpleLabel = false; /* Events */ /** * @event disable * * A 'disable' event is emitted when the disabled state of the widget changes * (i.e. on disable **and** enable). * * @param {boolean} disabled Widget is disabled */ /** * @event toggle * * A 'toggle' event is emitted when the visibility of the widget changes. * * @param {boolean} visible Widget is visible */ /* Methods */ /** * Check if the widget is disabled. * * @return {boolean} Widget is disabled */ OO.ui.Widget.prototype.isDisabled = function () { return this.disabled; }; /** * Set the 'disabled' state of the widget. * * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state. * * @param {boolean} disabled Disable widget * @chainable */ OO.ui.Widget.prototype.setDisabled = function ( disabled ) { var isDisabled; this.disabled = !!disabled; isDisabled = this.isDisabled(); if ( isDisabled !== this.wasDisabled ) { this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled ); this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled ); this.$element.attr( 'aria-disabled', isDisabled.toString() ); this.emit( 'disable', isDisabled ); this.updateThemeClasses(); } this.wasDisabled = isDisabled; return this; }; /** * Update the disabled state, in case of changes in parent widget. * * @chainable */ OO.ui.Widget.prototype.updateDisabled = function () { this.setDisabled( this.disabled ); return this; }; /** * Theme logic. * * @abstract * @class * * @constructor */ OO.ui.Theme = function OoUiTheme() { this.elementClassesQueue = []; this.debouncedUpdateQueuedElementClasses = OO.ui.debounce( this.updateQueuedElementClasses ); }; /* Setup */ OO.initClass( OO.ui.Theme ); /* Methods */ /** * Get a list of classes to be applied to a widget. * * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes, * otherwise state transitions will not work properly. * * @param {OO.ui.Element} element Element for which to get classes * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists */ OO.ui.Theme.prototype.getElementClasses = function () { return { on: [], off: [] }; }; /** * Update CSS classes provided by the theme. * * For elements with theme logic hooks, this should be called any time there's a state change. * * @param {OO.ui.Element} element Element for which to update classes */ OO.ui.Theme.prototype.updateElementClasses = function ( element ) { var $elements = $( [] ), classes = this.getElementClasses( element ); if ( element.$icon ) { $elements = $elements.add( element.$icon ); } if ( element.$indicator ) { $elements = $elements.add( element.$indicator ); } $elements .removeClass( classes.off.join( ' ' ) ) .addClass( classes.on.join( ' ' ) ); }; /** * @private */ OO.ui.Theme.prototype.updateQueuedElementClasses = function () { var i; for ( i = 0; i < this.elementClassesQueue.length; i++ ) { this.updateElementClasses( this.elementClassesQueue[ i ] ); } // Clear the queue this.elementClassesQueue = []; }; /** * Queue #updateElementClasses to be called for this element. * * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses, * to make them synchronous. * * @param {OO.ui.Element} element Element for which to update classes */ OO.ui.Theme.prototype.queueUpdateElementClasses = function ( element ) { // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's // the most common case (this method is often called repeatedly for the same element). if ( this.elementClassesQueue.lastIndexOf( element ) !== -1 ) { return; } this.elementClassesQueue.push( element ); this.debouncedUpdateQueuedElementClasses(); }; /** * Get the transition duration in milliseconds for dialogs opening/closing * * The dialog should be fully rendered this many milliseconds after the * ready process has executed. * * @return {number} Transition duration in milliseconds */ OO.ui.Theme.prototype.getDialogTransitionDuration = function () { return 0; }; /** * The TabIndexedElement class is an attribute mixin used to add additional functionality to an * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the * order in which users will navigate through the focusable elements via the "tab" key. * * @example * // TabIndexedElement is mixed into the ButtonWidget class * // to provide a tabIndex property. * var button1 = new OO.ui.ButtonWidget( { * label: 'fourth', * tabIndex: 4 * } ); * var button2 = new OO.ui.ButtonWidget( { * label: 'second', * tabIndex: 2 * } ); * var button3 = new OO.ui.ButtonWidget( { * label: 'third', * tabIndex: 3 * } ); * var button4 = new OO.ui.ButtonWidget( { * label: 'first', * tabIndex: 1 * } ); * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default, * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex * functionality will be applied to it instead. * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1 * to remove the element from the tab-navigation flow. */ OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) { // Configuration initialization config = $.extend( { tabIndex: 0 }, config ); // Properties this.$tabIndexed = null; this.tabIndex = null; // Events this.connect( this, { disable: 'onTabIndexedElementDisable' } ); // Initialization this.setTabIndex( config.tabIndex ); this.setTabIndexedElement( config.$tabIndexed || this.$element ); }; /* Setup */ OO.initClass( OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * Set the element that should use the tabindex functionality. * * This method is used to retarget a tabindex mixin so that its functionality applies * to the specified element. If an element is currently using the functionality, the mixin’s * effect on that element is removed before the new element is set up. * * @param {jQuery} $tabIndexed Element that should use the tabindex functionality * @chainable */ OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) { var tabIndex = this.tabIndex; // Remove attributes from old $tabIndexed this.setTabIndex( null ); // Force update of new $tabIndexed this.$tabIndexed = $tabIndexed; this.tabIndex = tabIndex; return this.updateTabIndex(); }; /** * Set the value of the tabindex. * * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex * @chainable */ OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) { tabIndex = typeof tabIndex === 'number' ? tabIndex : null; if ( this.tabIndex !== tabIndex ) { this.tabIndex = tabIndex; this.updateTabIndex(); } return this; }; /** * Update the `tabindex` attribute, in case of changes to tab index or * disabled state. * * @private * @chainable */ OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () { if ( this.$tabIndexed ) { if ( this.tabIndex !== null ) { // Do not index over disabled elements this.$tabIndexed.attr( { tabindex: this.isDisabled() ? -1 : this.tabIndex, // Support: ChromeVox and NVDA // These do not seem to inherit aria-disabled from parent elements 'aria-disabled': this.isDisabled().toString() } ); } else { this.$tabIndexed.removeAttr( 'tabindex aria-disabled' ); } } return this; }; /** * Handle disable events. * * @private * @param {boolean} disabled Element is disabled */ OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () { this.updateTabIndex(); }; /** * Get the value of the tabindex. * * @return {number|null} Tabindex value */ OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () { return this.tabIndex; }; /** * ButtonElement is often mixed into other classes to generate a button, which is a clickable * interface element that can be configured with access keys for accessibility. * See the [OOjs UI documentation on MediaWiki] [1] for examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$button] The button element created by the class. * If this configuration is omitted, the button element will use a generated `<a>`. * @cfg {boolean} [framed=true] Render the button with a frame */ OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) { // Configuration initialization config = config || {}; // Properties this.$button = null; this.framed = null; this.active = config.active !== undefined && config.active; this.onMouseUpHandler = this.onMouseUp.bind( this ); this.onMouseDownHandler = this.onMouseDown.bind( this ); this.onKeyDownHandler = this.onKeyDown.bind( this ); this.onKeyUpHandler = this.onKeyUp.bind( this ); this.onClickHandler = this.onClick.bind( this ); this.onKeyPressHandler = this.onKeyPress.bind( this ); // Initialization this.$element.addClass( 'oo-ui-buttonElement' ); this.toggleFramed( config.framed === undefined || config.framed ); this.setButtonElement( config.$button || $( '<a>' ) ); }; /* Setup */ OO.initClass( OO.ui.mixin.ButtonElement ); /* Static Properties */ /** * Cancel mouse down events. * * This property is usually set to `true` to prevent the focus from changing when the button is clicked. * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a * parent widget. * * @static * @inheritable * @property {boolean} */ OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true; /* Events */ /** * A 'click' event is emitted when the button element is clicked. * * @event click */ /* Methods */ /** * Set the button element. * * This method is used to retarget a button mixin so that its functionality applies to * the specified button element instead of the one created by the class. If a button element * is already set, the method will remove the mixin’s effect on that element. * * @param {jQuery} $button Element to use as button */ OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) { if ( this.$button ) { this.$button .removeClass( 'oo-ui-buttonElement-button' ) .removeAttr( 'role accesskey' ) .off( { mousedown: this.onMouseDownHandler, keydown: this.onKeyDownHandler, click: this.onClickHandler, keypress: this.onKeyPressHandler } ); } this.$button = $button .addClass( 'oo-ui-buttonElement-button' ) .on( { mousedown: this.onMouseDownHandler, keydown: this.onKeyDownHandler, click: this.onClickHandler, keypress: this.onKeyPressHandler } ); // Add `role="button"` on `<a>` elements, where it's needed // `toUppercase()` is added for XHTML documents if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) { this.$button.attr( 'role', 'button' ); } }; /** * Handles mouse down events. * * @protected * @param {jQuery.Event} e Mouse down event */ OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) { if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) { return; } this.$element.addClass( 'oo-ui-buttonElement-pressed' ); // Run the mouseup handler no matter where the mouse is when the button is let go, so we can // reliably remove the pressed class this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true ); // Prevent change of focus unless specifically configured otherwise if ( this.constructor.static.cancelButtonMouseDownEvents ) { return false; } }; /** * Handles mouse up events. * * @protected * @param {MouseEvent} e Mouse up event */ OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) { if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) { return; } this.$element.removeClass( 'oo-ui-buttonElement-pressed' ); // Stop listening for mouseup, since we only needed this once this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true ); }; /** * Handles mouse click events. * * @protected * @param {jQuery.Event} e Mouse click event * @fires click */ OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) { if ( this.emit( 'click' ) ) { return false; } } }; /** * Handles key down events. * * @protected * @param {jQuery.Event} e Key down event */ OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) { if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) { return; } this.$element.addClass( 'oo-ui-buttonElement-pressed' ); // Run the keyup handler no matter where the key is when the button is let go, so we can // reliably remove the pressed class this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true ); }; /** * Handles key up events. * * @protected * @param {KeyboardEvent} e Key up event */ OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) { if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) { return; } this.$element.removeClass( 'oo-ui-buttonElement-pressed' ); // Stop listening for keyup, since we only needed this once this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true ); }; /** * Handles key press events. * * @protected * @param {jQuery.Event} e Key press event * @fires click */ OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { if ( this.emit( 'click' ) ) { return false; } } }; /** * Check if button has a frame. * * @return {boolean} Button is framed */ OO.ui.mixin.ButtonElement.prototype.isFramed = function () { return this.framed; }; /** * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off. * * @param {boolean} [framed] Make button framed, omit to toggle * @chainable */ OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) { framed = framed === undefined ? !this.framed : !!framed; if ( framed !== this.framed ) { this.framed = framed; this.$element .toggleClass( 'oo-ui-buttonElement-frameless', !framed ) .toggleClass( 'oo-ui-buttonElement-framed', framed ); this.updateThemeClasses(); } return this; }; /** * Set the button's active state. * * The active state can be set on: * * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page * * @protected * @param {boolean} value Make button active * @chainable */ OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) { this.active = !!value; this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active ); this.updateThemeClasses(); return this; }; /** * Check if the button is active * * @protected * @return {boolean} The button is active */ OO.ui.mixin.ButtonElement.prototype.isActive = function () { return this.active; }; /** * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing * items from the group is done through the interface the class provides. * For more information, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$group] The container element created by the class. If this configuration * is omitted, the group element will use a generated `<div>`. */ OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) { // Configuration initialization config = config || {}; // Properties this.$group = null; this.items = []; this.aggregateItemEvents = {}; // Initialization this.setGroupElement( config.$group || $( '<div>' ) ); }; /* Events */ /** * @event change * * A change event is emitted when the set of selected items changes. * * @param {OO.ui.Element[]} items Items currently in the group */ /* Methods */ /** * Set the group element. * * If an element is already set, items will be moved to the new element. * * @param {jQuery} $group Element to use as group */ OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) { var i, len; this.$group = $group; for ( i = 0, len = this.items.length; i < len; i++ ) { this.$group.append( this.items[ i ].$element ); } }; /** * Check if a group contains no items. * * @return {boolean} Group is empty */ OO.ui.mixin.GroupElement.prototype.isEmpty = function () { return !this.items.length; }; /** * Get all items in the group. * * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful * when synchronizing groups of items, or whenever the references are required (e.g., when removing items * from a group). * * @return {OO.ui.Element[]} An array of items. */ OO.ui.mixin.GroupElement.prototype.getItems = function () { return this.items.slice( 0 ); }; /** * Get an item by its data. * * Only the first item with matching data will be returned. To return all matching items, * use the #getItemsFromData method. * * @param {Object} data Item data to search for * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists */ OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) { var i, len, item, hash = OO.getHash( data ); for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( hash === OO.getHash( item.getData() ) ) { return item; } } return null; }; /** * Get items by their data. * * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead. * * @param {Object} data Item data to search for * @return {OO.ui.Element[]} Items with equivalent data */ OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) { var i, len, item, hash = OO.getHash( data ), items = []; for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( hash === OO.getHash( item.getData() ) ) { items.push( item ); } } return items; }; /** * Aggregate the events emitted by the group. * * When events are aggregated, the group will listen to all contained items for the event, * and then emit the event under a new name. The new event will contain an additional leading * parameter containing the item that emitted the original event. Other arguments emitted from * the original event are passed through. * * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’). * A `null` value will remove aggregated events. * @throws {Error} An error is thrown if aggregation already exists. */ OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) { var i, len, item, add, remove, itemEvent, groupEvent; for ( itemEvent in events ) { groupEvent = events[ itemEvent ]; // Remove existing aggregated event if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) { // Don't allow duplicate aggregations if ( groupEvent ) { throw new Error( 'Duplicate item event aggregation for ' + itemEvent ); } // Remove event aggregation from existing items for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item.connect && item.disconnect ) { remove = {}; remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; item.disconnect( this, remove ); } } // Prevent future items from aggregating event delete this.aggregateItemEvents[ itemEvent ]; } // Add new aggregate event if ( groupEvent ) { // Make future items aggregate event this.aggregateItemEvents[ itemEvent ] = groupEvent; // Add event aggregation to existing items for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item.connect && item.disconnect ) { add = {}; add[ itemEvent ] = [ 'emit', groupEvent, item ]; item.connect( this, add ); } } } } }; /** * Add items to the group. * * Items will be added to the end of the group array unless the optional `index` parameter specifies * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`. * * @param {OO.ui.Element[]} items An array of items to add to the group * @param {number} [index] Index of the insertion point * @chainable */ OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) { var i, len, item, itemEvent, events, currentIndex, itemElements = []; for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; // Check if item exists then remove it first, effectively "moving" it currentIndex = this.items.indexOf( item ); if ( currentIndex >= 0 ) { this.removeItems( [ item ] ); // Adjust index to compensate for removal if ( currentIndex < index ) { index--; } } // Add the item if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) { events = {}; for ( itemEvent in this.aggregateItemEvents ) { events[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; } item.connect( this, events ); } item.setElementGroup( this ); itemElements.push( item.$element.get( 0 ) ); } if ( index === undefined || index < 0 || index >= this.items.length ) { this.$group.append( itemElements ); this.items.push.apply( this.items, items ); } else if ( index === 0 ) { this.$group.prepend( itemElements ); this.items.unshift.apply( this.items, items ); } else { this.items[ index ].$element.before( itemElements ); this.items.splice.apply( this.items, [ index, 0 ].concat( items ) ); } this.emit( 'change', this.getItems() ); return this; }; /** * Remove the specified items from a group. * * Removed items are detached (not removed) from the DOM so that they may be reused. * To remove all items from a group, you may wish to use the #clearItems method instead. * * @param {OO.ui.Element[]} items An array of items to remove * @chainable */ OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) { var i, len, item, index, events, itemEvent; // Remove specific items for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; index = this.items.indexOf( item ); if ( index !== -1 ) { if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) { events = {}; for ( itemEvent in this.aggregateItemEvents ) { events[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; } item.disconnect( this, events ); } item.setElementGroup( null ); this.items.splice( index, 1 ); item.$element.detach(); } } this.emit( 'change', this.getItems() ); return this; }; /** * Clear all items from the group. * * Cleared items are detached from the DOM, not removed, so that they may be reused. * To remove only a subset of items from a group, use the #removeItems method. * * @chainable */ OO.ui.mixin.GroupElement.prototype.clearItems = function () { var i, len, item, remove, itemEvent; // Remove all items for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) { remove = {}; if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) { remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; } item.disconnect( this, remove ); } item.setElementGroup( null ); item.$element.detach(); } this.emit( 'change', this.getItems() ); this.items = []; return this; }; /** * IconElement is often mixed into other classes to generate an icon. * Icons are graphics, about the size of normal text. They are used to aid the user * in locating a control or to convey information in a space-efficient way. See the * [OOjs UI documentation on MediaWiki] [1] for a list of icons * included in the library. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted, * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that * the icon element be set to an existing icon instead of the one generated by this class, set a * value using a jQuery selection. For example: * * // Use a <div> tag instead of a <span> * $icon: $("<div>") * // Use an existing icon element instead of the one generated by the class * $icon: this.$element * // Use an icon element from a child widget * $icon: this.childwidget.$element * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of * symbolic names. A map is used for i18n purposes and contains a `default` icon * name and additional names keyed by language code. The `default` name is used when no icon is keyed * by the user's language. * * Example of an i18n map: * * { default: 'bold-a', en: 'bold-b', de: 'bold-f' } * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title * text. The icon title is displayed when users move the mouse over the icon. */ OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) { // Configuration initialization config = config || {}; // Properties this.$icon = null; this.icon = null; this.iconTitle = null; // Initialization this.setIcon( config.icon || this.constructor.static.icon ); this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle ); this.setIconElement( config.$icon || $( '<span>' ) ); }; /* Setup */ OO.initClass( OO.ui.mixin.IconElement ); /* Static Properties */ /** * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used * for i18n purposes and contains a `default` icon name and additional names keyed by * language code. The `default` name is used when no icon is keyed by the user's language. * * Example of an i18n map: * * { default: 'bold-a', en: 'bold-b', de: 'bold-f' } * * Note: the static property will be overridden if the #icon configuration is used. * * @static * @inheritable * @property {Object|string} */ OO.ui.mixin.IconElement.static.icon = null; /** * The icon title, displayed when users move the mouse over the icon. The value can be text, a * function that returns title text, or `null` for no title. * * The static property will be overridden if the #iconTitle configuration is used. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.IconElement.static.iconTitle = null; /* Methods */ /** * Set the icon element. This method is used to retarget an icon mixin so that its functionality * applies to the specified icon element instead of the one created by the class. If an icon * element is already set, the mixin’s effect on that element is removed. Generated CSS classes * and mixin methods will no longer affect the element. * * @param {jQuery} $icon Element to use as icon */ OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) { if ( this.$icon ) { this.$icon .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon ) .removeAttr( 'title' ); } this.$icon = $icon .addClass( 'oo-ui-iconElement-icon' ) .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon ); if ( this.iconTitle !== null ) { this.$icon.attr( 'title', this.iconTitle ); } this.updateThemeClasses(); }; /** * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon. * The icon parameter can also be set to a map of icon names. See the #icon config setting * for an example. * * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed * by language code, or `null` to remove the icon. * @chainable */ OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) { icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon; icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null; if ( this.icon !== icon ) { if ( this.$icon ) { if ( this.icon !== null ) { this.$icon.removeClass( 'oo-ui-icon-' + this.icon ); } if ( icon !== null ) { this.$icon.addClass( 'oo-ui-icon-' + icon ); } } this.icon = icon; } this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon ); this.updateThemeClasses(); return this; }; /** * Set the icon title. Use `null` to remove the title. * * @param {string|Function|null} iconTitle A text string used as the icon title, * a function that returns title text, or `null` for no title. * @chainable */ OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) { iconTitle = typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ? OO.ui.resolveMsg( iconTitle ) : null; if ( this.iconTitle !== iconTitle ) { this.iconTitle = iconTitle; if ( this.$icon ) { if ( this.iconTitle !== null ) { this.$icon.attr( 'title', iconTitle ); } else { this.$icon.removeAttr( 'title' ); } } } return this; }; /** * Get the symbolic name of the icon. * * @return {string} Icon name */ OO.ui.mixin.IconElement.prototype.getIcon = function () { return this.icon; }; /** * Get the icon title. The title text is displayed when a user moves the mouse over the icon. * * @return {string} Icon title text */ OO.ui.mixin.IconElement.prototype.getIconTitle = function () { return this.iconTitle; }; /** * IndicatorElement is often mixed into other classes to generate an indicator. * Indicators are small graphics that are generally used in two ways: * * - To draw attention to the status of an item. For example, an indicator might be * used to show that an item in a list has errors that need to be resolved. * - To clarify the function of a control that acts in an exceptional way (a button * that opens a menu instead of performing an action directly, for example). * * For a list of indicators included in the library, please see the * [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$indicator] The indicator element created by the class. If this * configuration is omitted, the indicator element will use a generated `<span>`. * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’). * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included * in the library. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title, * or a function that returns title text. The indicator title is displayed when users move * the mouse over the indicator. */ OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) { // Configuration initialization config = config || {}; // Properties this.$indicator = null; this.indicator = null; this.indicatorTitle = null; // Initialization this.setIndicator( config.indicator || this.constructor.static.indicator ); this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle ); this.setIndicatorElement( config.$indicator || $( '<span>' ) ); }; /* Setup */ OO.initClass( OO.ui.mixin.IndicatorElement ); /* Static Properties */ /** * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’). * The static property will be overridden if the #indicator configuration is used. * * @static * @inheritable * @property {string|null} */ OO.ui.mixin.IndicatorElement.static.indicator = null; /** * A text string used as the indicator title, a function that returns title text, or `null` * for no title. The static property will be overridden if the #indicatorTitle configuration is used. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.IndicatorElement.static.indicatorTitle = null; /* Methods */ /** * Set the indicator element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $indicator Element to use as indicator */ OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) { if ( this.$indicator ) { this.$indicator .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator ) .removeAttr( 'title' ); } this.$indicator = $indicator .addClass( 'oo-ui-indicatorElement-indicator' ) .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator ); if ( this.indicatorTitle !== null ) { this.$indicator.attr( 'title', this.indicatorTitle ); } this.updateThemeClasses(); }; /** * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator. * * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator * @chainable */ OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) { indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null; if ( this.indicator !== indicator ) { if ( this.$indicator ) { if ( this.indicator !== null ) { this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator ); } if ( indicator !== null ) { this.$indicator.addClass( 'oo-ui-indicator-' + indicator ); } } this.indicator = indicator; } this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator ); this.updateThemeClasses(); return this; }; /** * Set the indicator title. * * The title is displayed when a user moves the mouse over the indicator. * * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or * `null` for no indicator title * @chainable */ OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) { indicatorTitle = typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ? OO.ui.resolveMsg( indicatorTitle ) : null; if ( this.indicatorTitle !== indicatorTitle ) { this.indicatorTitle = indicatorTitle; if ( this.$indicator ) { if ( this.indicatorTitle !== null ) { this.$indicator.attr( 'title', indicatorTitle ); } else { this.$indicator.removeAttr( 'title' ); } } } return this; }; /** * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’). * * @return {string} Symbolic name of indicator */ OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () { return this.indicator; }; /** * Get the indicator title. * * The title is displayed when a user moves the mouse over the indicator. * * @return {string} Indicator title text */ OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () { return this.indicatorTitle; }; /** * LabelElement is often mixed into other classes to generate a label, which * helps identify the function of an interface element. * See the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$label] The label element created by the class. If this * configuration is omitted, the label element will use a generated `<span>`. * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified * as a plaintext string, a jQuery selection of elements, or a function that will produce a string * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels */ OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) { // Configuration initialization config = config || {}; // Properties this.$label = null; this.label = null; // Initialization this.setLabel( config.label || this.constructor.static.label ); this.setLabelElement( config.$label || $( '<span>' ) ); }; /* Setup */ OO.initClass( OO.ui.mixin.LabelElement ); /* Events */ /** * @event labelChange * @param {string} value */ /* Static Properties */ /** * The label text. The label can be specified as a plaintext string, a function that will * produce a string in the future, or `null` for no label. The static value will * be overridden if a label is specified with the #label config option. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.LabelElement.static.label = null; /* Static methods */ /** * Highlight the first occurrence of the query in the given text * * @param {string} text Text * @param {string} query Query to find * @return {jQuery} Text with the first match of the query * sub-string wrapped in highlighted span */ OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query ) { var $result = $( '<span>' ), offset = text.toLowerCase().indexOf( query.toLowerCase() ); if ( !query.length || offset === -1 ) { return $result.text( text ); } $result.append( document.createTextNode( text.slice( 0, offset ) ), $( '<span>' ) .addClass( 'oo-ui-labelElement-label-highlight' ) .text( text.slice( offset, offset + query.length ) ), document.createTextNode( text.slice( offset + query.length ) ) ); return $result.contents(); }; /* Methods */ /** * Set the label element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $label Element to use as label */ OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) { if ( this.$label ) { this.$label.removeClass( 'oo-ui-labelElement-label' ).empty(); } this.$label = $label.addClass( 'oo-ui-labelElement-label' ); this.setLabelContent( this.label ); }; /** * Set the label. * * An empty string will result in the label being hidden. A string containing only whitespace will * be converted to a single `&nbsp;`. * * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or * text; or null for no label * @chainable */ OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) { label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label; label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null; if ( this.label !== label ) { if ( this.$label ) { this.setLabelContent( label ); } this.label = label; this.emit( 'labelChange' ); } this.$element.toggleClass( 'oo-ui-labelElement', !!this.label ); return this; }; /** * Set the label as plain text with a highlighted query * * @param {string} text Text label to set * @param {string} query Substring of text to highlight * @chainable */ OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query ) { return this.setLabel( this.constructor.static.highlightQuery( text, query ) ); }; /** * Get the label. * * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or * text; or null for no label */ OO.ui.mixin.LabelElement.prototype.getLabel = function () { return this.label; }; /** * Set the content of the label. * * Do not call this method until after the label element has been set by #setLabelElement. * * @private * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or * text; or null for no label */ OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) { if ( typeof label === 'string' ) { if ( label.match( /^\s*$/ ) ) { // Convert whitespace only string to a single non-breaking space this.$label.html( '&nbsp;' ); } else { this.$label.text( label ); } } else if ( label instanceof OO.ui.HtmlSnippet ) { this.$label.html( label.toString() ); } else if ( label instanceof jQuery ) { this.$label.empty().append( label ); } else { this.$label.empty(); } }; /** * The FlaggedElement class is an attribute mixin, meaning that it is used to add * additional functionality to an element created by another class. The class provides * a ‘flags’ property assigned the name (or an array of names) of styling flags, * which are used to customize the look and feel of a widget to better describe its * importance and functionality. * * The library currently contains the following styling flags for general use: * * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process. * - **destructive**: Destructive styling is applied to convey that the widget will remove something. * - **constructive**: Constructive styling is applied to convey that the widget will create something. * * The flags affect the appearance of the buttons: * * @example * // FlaggedElement is mixed into ButtonWidget to provide styling flags * var button1 = new OO.ui.ButtonWidget( { * label: 'Constructive', * flags: 'constructive' * } ); * var button2 = new OO.ui.ButtonWidget( { * label: 'Destructive', * flags: 'destructive' * } ); * var button3 = new OO.ui.ButtonWidget( { * label: 'Progressive', * flags: 'progressive' * } ); * $( 'body' ).append( button1.$element, button2.$element, button3.$element ); * * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply. * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged * @cfg {jQuery} [$flagged] The flagged element. By default, * the flagged functionality is applied to the element created by the class ($element). * If a different element is specified, the flagged functionality will be applied to it instead. */ OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) { // Configuration initialization config = config || {}; // Properties this.flags = {}; this.$flagged = null; // Initialization this.setFlags( config.flags ); this.setFlaggedElement( config.$flagged || this.$element ); }; /* Events */ /** * @event flag * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes` * parameter contains the name of each modified flag and indicates whether it was * added or removed. * * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates * that the flag was added, `false` that the flag was removed. */ /* Methods */ /** * Set the flagged element. * * This method is used to retarget a flagged mixin so that its functionality applies to the specified element. * If an element is already set, the method will remove the mixin’s effect on that element. * * @param {jQuery} $flagged Element that should be flagged */ OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) { var classNames = Object.keys( this.flags ).map( function ( flag ) { return 'oo-ui-flaggedElement-' + flag; } ).join( ' ' ); if ( this.$flagged ) { this.$flagged.removeClass( classNames ); } this.$flagged = $flagged.addClass( classNames ); }; /** * Check if the specified flag is set. * * @param {string} flag Name of flag * @return {boolean} The flag is set */ OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) { // This may be called before the constructor, thus before this.flags is set return this.flags && ( flag in this.flags ); }; /** * Get the names of all flags set. * * @return {string[]} Flag names */ OO.ui.mixin.FlaggedElement.prototype.getFlags = function () { // This may be called before the constructor, thus before this.flags is set return Object.keys( this.flags || {} ); }; /** * Clear all flags. * * @chainable * @fires flag */ OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () { var flag, className, changes = {}, remove = [], classPrefix = 'oo-ui-flaggedElement-'; for ( flag in this.flags ) { className = classPrefix + flag; changes[ flag ] = false; delete this.flags[ flag ]; remove.push( className ); } if ( this.$flagged ) { this.$flagged.removeClass( remove.join( ' ' ) ); } this.updateThemeClasses(); this.emit( 'flag', changes ); return this; }; /** * Add one or more flags. * * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names, * or an object keyed by flag name with a boolean value that indicates whether the flag should * be added (`true`) or removed (`false`). * @chainable * @fires flag */ OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) { var i, len, flag, className, changes = {}, add = [], remove = [], classPrefix = 'oo-ui-flaggedElement-'; if ( typeof flags === 'string' ) { className = classPrefix + flags; // Set if ( !this.flags[ flags ] ) { this.flags[ flags ] = true; add.push( className ); } } else if ( Array.isArray( flags ) ) { for ( i = 0, len = flags.length; i < len; i++ ) { flag = flags[ i ]; className = classPrefix + flag; // Set if ( !this.flags[ flag ] ) { changes[ flag ] = true; this.flags[ flag ] = true; add.push( className ); } } } else if ( OO.isPlainObject( flags ) ) { for ( flag in flags ) { className = classPrefix + flag; if ( flags[ flag ] ) { // Set if ( !this.flags[ flag ] ) { changes[ flag ] = true; this.flags[ flag ] = true; add.push( className ); } } else { // Remove if ( this.flags[ flag ] ) { changes[ flag ] = false; delete this.flags[ flag ]; remove.push( className ); } } } } if ( this.$flagged ) { this.$flagged .addClass( add.join( ' ' ) ) .removeClass( remove.join( ' ' ) ); } this.updateThemeClasses(); this.emit( 'flag', changes ); return this; }; /** * TitledElement is mixed into other classes to provide a `title` attribute. * Titles are rendered by the browser and are made visible when the user moves * the mouse over the element. Titles are not visible on touch devices. * * @example * // TitledElement provides a 'title' attribute to the * // ButtonWidget class * var button = new OO.ui.ButtonWidget( { * label: 'Button with Title', * title: 'I am a button' * } ); * $( 'body' ).append( button.$element ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied. * If this config is omitted, the title functionality is applied to $element, the * element created by the class. * @cfg {string|Function} [title] The title text or a function that returns text. If * this config is omitted, the value of the {@link #static-title static title} property is used. */ OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) { // Configuration initialization config = config || {}; // Properties this.$titled = null; this.title = null; // Initialization this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title ); this.setTitledElement( config.$titled || this.$element ); }; /* Setup */ OO.initClass( OO.ui.mixin.TitledElement ); /* Static Properties */ /** * The title text, a function that returns text, or `null` for no title. The value of the static property * is overridden if the #title config option is used. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.TitledElement.static.title = null; /* Methods */ /** * Set the titled element. * * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element. * If an element is already set, the mixin’s effect on that element is removed before the new element is set up. * * @param {jQuery} $titled Element that should use the 'titled' functionality */ OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) { if ( this.$titled ) { this.$titled.removeAttr( 'title' ); } this.$titled = $titled; if ( this.title ) { this.$titled.attr( 'title', this.title ); } }; /** * Set title. * * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title * @chainable */ OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) { title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title; title = ( typeof title === 'string' && title.length ) ? title : null; if ( this.title !== title ) { if ( this.$titled ) { if ( title !== null ) { this.$titled.attr( 'title', title ); } else { this.$titled.removeAttr( 'title' ); } } this.title = title; } return this; }; /** * Get title. * * @return {string} Title string */ OO.ui.mixin.TitledElement.prototype.getTitle = function () { return this.title; }; /** * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute. * Accesskeys allow an user to go to a specific element by using * a shortcut combination of a browser specific keys + the key * set to the field. * * @example * // AccessKeyedElement provides an 'accesskey' attribute to the * // ButtonWidget class * var button = new OO.ui.ButtonWidget( { * label: 'Button with Accesskey', * accessKey: 'k' * } ); * $( 'body' ).append( button.$element ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied. * If this config is omitted, the accesskey functionality is applied to $element, the * element created by the class. * @cfg {string|Function} [accessKey] The key or a function that returns the key. If * this config is omitted, no accesskey will be added. */ OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) { // Configuration initialization config = config || {}; // Properties this.$accessKeyed = null; this.accessKey = null; // Initialization this.setAccessKey( config.accessKey || null ); this.setAccessKeyedElement( config.$accessKeyed || this.$element ); }; /* Setup */ OO.initClass( OO.ui.mixin.AccessKeyedElement ); /* Static Properties */ /** * The access key, a function that returns a key, or `null` for no accesskey. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.AccessKeyedElement.static.accessKey = null; /* Methods */ /** * Set the accesskeyed element. * * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element. * If an element is already set, the mixin's effect on that element is removed before the new element is set up. * * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality */ OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) { if ( this.$accessKeyed ) { this.$accessKeyed.removeAttr( 'accesskey' ); } this.$accessKeyed = $accessKeyed; if ( this.accessKey ) { this.$accessKeyed.attr( 'accesskey', this.accessKey ); } }; /** * Set accesskey. * * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey * @chainable */ OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) { accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null; if ( this.accessKey !== accessKey ) { if ( this.$accessKeyed ) { if ( accessKey !== null ) { this.$accessKeyed.attr( 'accesskey', accessKey ); } else { this.$accessKeyed.removeAttr( 'accesskey' ); } } this.accessKey = accessKey; } return this; }; /** * Get accesskey. * * @return {string} accessKey string */ OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () { return this.accessKey; }; /** * ButtonWidget is a generic widget for buttons. A wide variety of looks, * feels, and functionality can be customized via the class’s configuration options * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information * and examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches * * @example * // A button widget * var button = new OO.ui.ButtonWidget( { * label: 'Button with Icon', * icon: 'remove', * iconTitle: 'Remove' * } ); * $( 'body' ).append( button.$element ); * * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class. * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.ButtonElement * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.TabIndexedElement * @mixins OO.ui.mixin.AccessKeyedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [active=false] Whether button should be shown as active * @cfg {string} [href] Hyperlink to visit when the button is clicked. * @cfg {string} [target] The frame or window in which to open the hyperlink. * @cfg {boolean} [noFollow] Search engine traversal hint (default: true) */ OO.ui.ButtonWidget = function OoUiButtonWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ButtonWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ButtonElement.call( this, config ); OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) ); OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) ); // Properties this.href = null; this.target = null; this.noFollow = false; // Events this.connect( this, { disable: 'onDisable' } ); // Initialization this.$button.append( this.$icon, this.$label, this.$indicator ); this.$element .addClass( 'oo-ui-buttonWidget' ) .append( this.$button ); this.setActive( config.active ); this.setHref( config.href ); this.setTarget( config.target ); this.setNoFollow( config.noFollow ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false; /* Methods */ /** * Get hyperlink location. * * @return {string} Hyperlink location */ OO.ui.ButtonWidget.prototype.getHref = function () { return this.href; }; /** * Get hyperlink target. * * @return {string} Hyperlink target */ OO.ui.ButtonWidget.prototype.getTarget = function () { return this.target; }; /** * Get search engine traversal hint. * * @return {boolean} Whether search engines should avoid traversing this hyperlink */ OO.ui.ButtonWidget.prototype.getNoFollow = function () { return this.noFollow; }; /** * Set hyperlink location. * * @param {string|null} href Hyperlink location, null to remove */ OO.ui.ButtonWidget.prototype.setHref = function ( href ) { href = typeof href === 'string' ? href : null; if ( href !== null && !OO.ui.isSafeUrl( href ) ) { href = './' + href; } if ( href !== this.href ) { this.href = href; this.updateHref(); } return this; }; /** * Update the `href` attribute, in case of changes to href or * disabled state. * * @private * @chainable */ OO.ui.ButtonWidget.prototype.updateHref = function () { if ( this.href !== null && !this.isDisabled() ) { this.$button.attr( 'href', this.href ); } else { this.$button.removeAttr( 'href' ); } return this; }; /** * Handle disable events. * * @private * @param {boolean} disabled Element is disabled */ OO.ui.ButtonWidget.prototype.onDisable = function () { this.updateHref(); }; /** * Set hyperlink target. * * @param {string|null} target Hyperlink target, null to remove */ OO.ui.ButtonWidget.prototype.setTarget = function ( target ) { target = typeof target === 'string' ? target : null; if ( target !== this.target ) { this.target = target; if ( target !== null ) { this.$button.attr( 'target', target ); } else { this.$button.removeAttr( 'target' ); } } return this; }; /** * Set search engine traversal hint. * * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink */ OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) { noFollow = typeof noFollow === 'boolean' ? noFollow : true; if ( noFollow !== this.noFollow ) { this.noFollow = noFollow; if ( noFollow ) { this.$button.attr( 'rel', 'nofollow' ); } else { this.$button.removeAttr( 'rel' ); } } return this; }; // Override method visibility hints from ButtonElement /** * @method setActive */ /** * @method isActive */ /** * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added, * removed, and cleared from the group. * * @example * // Example: A ButtonGroupWidget with two buttons * var button1 = new OO.ui.PopupButtonWidget( { * label: 'Select a category', * icon: 'menu', * popup: { * $content: $( '<p>List of categories...</p>' ), * padded: true, * align: 'left' * } * } ); * var button2 = new OO.ui.ButtonWidget( { * label: 'Add item' * }); * var buttonGroup = new OO.ui.ButtonGroupWidget( { * items: [button1, button2] * } ); * $( 'body' ).append( buttonGroup.$element ); * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add */ OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ButtonGroupWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-buttonGroupWidget' ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement ); /** * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget, * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1] * for a list of icons included in the library. * * @example * // An icon widget with a label * var myIcon = new OO.ui.IconWidget( { * icon: 'help', * iconTitle: 'Help' * } ); * // Create a label. * var iconLabel = new OO.ui.LabelWidget( { * label: 'Help' * } ); * $( 'body' ).append( myIcon.$element, iconLabel.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.FlaggedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.IconWidget = function OoUiIconWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.IconWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) ); OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-iconWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.IconWidget.static.tagName = 'span'; /** * IndicatorWidgets create indicators, which are small graphics that are generally used to draw * attention to the status of an item or to clarify the function of a control. For a list of * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example of an indicator widget * var indicator1 = new OO.ui.IndicatorWidget( { * indicator: 'alert' * } ); * * // Create a fieldset layout to add a label * var fieldset = new OO.ui.FieldsetLayout(); * fieldset.addItems( [ * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } ) * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.IndicatorWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-indicatorWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.IndicatorWidget.static.tagName = 'span'; /** * LabelWidgets help identify the function of interface elements. Each LabelWidget can * be configured with a `label` option that is set to a string, a label node, or a function: * * - String: a plaintext string * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a * label that includes a link or special styling, such as a gray color or additional graphical elements. * - Function: a function that will produce a string in the future. Functions are used * in cases where the value of the label is not currently defined. * * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which * will come into focus when the label is clicked. * * @example * // Examples of LabelWidgets * var label1 = new OO.ui.LabelWidget( { * label: 'plaintext label' * } ); * var label2 = new OO.ui.LabelWidget( { * label: $( '<a href="default.html">jQuery label</a>' ) * } ); * // Create a fieldset layout with fields for each example * var fieldset = new OO.ui.FieldsetLayout(); * fieldset.addItems( [ * new OO.ui.FieldLayout( label1 ), * new OO.ui.FieldLayout( label2 ) * ] ); * $( 'body' ).append( fieldset.$element ); * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label. * Clicking the label will focus the specified input field. */ OO.ui.LabelWidget = function OoUiLabelWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.LabelWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) ); OO.ui.mixin.TitledElement.call( this, config ); // Properties this.input = config.input; // Initialization if ( this.input instanceof OO.ui.InputWidget ) { if ( this.input.getInputId() ) { this.$element.attr( 'for', this.input.getInputId() ); } else { this.$label.on( 'click', function () { this.fieldWidget.focus(); return false; }.bind( this ) ); } } this.$element.addClass( 'oo-ui-labelWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.LabelWidget.static.tagName = 'label'; /** * PendingElement is a mixin that is used to create elements that notify users that something is happening * and that they should wait before proceeding. The pending state is visually represented with a pending * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input * field of a {@link OO.ui.TextInputWidget text input widget}. * * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used * in process dialogs. * * @example * function MessageDialog( config ) { * MessageDialog.parent.call( this, config ); * } * OO.inheritClass( MessageDialog, OO.ui.MessageDialog ); * * MessageDialog.static.name = 'myMessageDialog'; * MessageDialog.static.actions = [ * { action: 'save', label: 'Done', flags: 'primary' }, * { label: 'Cancel', flags: 'safe' } * ]; * * MessageDialog.prototype.initialize = function () { * MessageDialog.parent.prototype.initialize.apply( this, arguments ); * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } ); * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' ); * this.$body.append( this.content.$element ); * }; * MessageDialog.prototype.getBodyHeight = function () { * return 100; * } * MessageDialog.prototype.getActionProcess = function ( action ) { * var dialog = this; * if ( action === 'save' ) { * dialog.getActions().get({actions: 'save'})[0].pushPending(); * return new OO.ui.Process() * .next( 1000 ) * .next( function () { * dialog.getActions().get({actions: 'save'})[0].popPending(); * } ); * } * return MessageDialog.parent.prototype.getActionProcess.call( this, action ); * }; * * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * * var dialog = new MessageDialog(); * windowManager.addWindows( [ dialog ] ); * windowManager.openWindow( dialog ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element */ OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) { // Configuration initialization config = config || {}; // Properties this.pending = 0; this.$pending = null; // Initialisation this.setPendingElement( config.$pending || this.$element ); }; /* Setup */ OO.initClass( OO.ui.mixin.PendingElement ); /* Methods */ /** * Set the pending element (and clean up any existing one). * * @param {jQuery} $pending The element to set to pending. */ OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) { if ( this.$pending ) { this.$pending.removeClass( 'oo-ui-pendingElement-pending' ); } this.$pending = $pending; if ( this.pending > 0 ) { this.$pending.addClass( 'oo-ui-pendingElement-pending' ); } }; /** * Check if an element is pending. * * @return {boolean} Element is pending */ OO.ui.mixin.PendingElement.prototype.isPending = function () { return !!this.pending; }; /** * Increase the pending counter. The pending state will remain active until the counter is zero * (i.e., the number of calls to #pushPending and #popPending is the same). * * @chainable */ OO.ui.mixin.PendingElement.prototype.pushPending = function () { if ( this.pending === 0 ) { this.$pending.addClass( 'oo-ui-pendingElement-pending' ); this.updateThemeClasses(); } this.pending++; return this; }; /** * Decrease the pending counter. The pending state will remain active until the counter is zero * (i.e., the number of calls to #pushPending and #popPending is the same). * * @chainable */ OO.ui.mixin.PendingElement.prototype.popPending = function () { if ( this.pending === 1 ) { this.$pending.removeClass( 'oo-ui-pendingElement-pending' ); this.updateThemeClasses(); } this.pending = Math.max( 0, this.pending - 1 ); return this; }; /** * Element that will stick under a specified container, even when it is inserted elsewhere in the * document (for example, in a OO.ui.Window's $overlay). * * The elements's position is automatically calculated and maintained when window is resized or the * page is scrolled. If you reposition the container manually, you have to call #position to make * sure the element is still placed correctly. * * As positioning is only possible when both the element and the container are attached to the DOM * and visible, it's only done after you call #togglePositioning. You might want to do this inside * the #toggle method to display a floating popup, for example. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element * @cfg {jQuery} [$floatableContainer] Node to position below */ OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) { // Configuration initialization config = config || {}; // Properties this.$floatable = null; this.$floatableContainer = null; this.$floatableWindow = null; this.$floatableClosestScrollable = null; this.onFloatableScrollHandler = this.position.bind( this ); this.onFloatableWindowResizeHandler = this.position.bind( this ); // Initialization this.setFloatableContainer( config.$floatableContainer ); this.setFloatableElement( config.$floatable || this.$element ); }; /* Methods */ /** * Set floatable element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $floatable Element to make floatable */ OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) { if ( this.$floatable ) { this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' ); this.$floatable.css( { left: '', top: '' } ); } this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' ); this.position(); }; /** * Set floatable container. * * The element will be always positioned under the specified container. * * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset */ OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) { this.$floatableContainer = $floatableContainer; if ( this.$floatable ) { this.position(); } }; /** * Toggle positioning. * * Do not turn positioning on until after the element is attached to the DOM and visible. * * @param {boolean} [positioning] Enable positioning, omit to toggle * @chainable */ OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) { var closestScrollableOfContainer; if ( !this.$floatable || !this.$floatableContainer ) { return this; } positioning = positioning === undefined ? !this.positioning : !!positioning; if ( positioning && !this.warnedUnattached && !this.isElementAttached() ) { OO.ui.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' ); this.warnedUnattached = true; } if ( this.positioning !== positioning ) { this.positioning = positioning; closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] ); this.needsCustomPosition = !OO.ui.contains( this.$floatableContainer[ 0 ], this.$floatable[ 0 ] ); // If the scrollable is the root, we have to listen to scroll events // on the window because of browser inconsistencies. if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) { closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer ); } if ( positioning ) { this.$floatableWindow = $( this.getElementWindow() ); this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler ); this.$floatableClosestScrollable = $( closestScrollableOfContainer ); this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler ); // Initial position after visible this.position(); } else { if ( this.$floatableWindow ) { this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler ); this.$floatableWindow = null; } if ( this.$floatableClosestScrollable ) { this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler ); this.$floatableClosestScrollable = null; } this.$floatable.css( { left: '', right: '', top: '' } ); } } return this; }; /** * Check whether the bottom edge of the given element is within the viewport of the given container. * * @private * @param {jQuery} $element * @param {jQuery} $container * @return {boolean} */ OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) { var elemRect, contRect, leftEdgeInBounds = false, bottomEdgeInBounds = false, rightEdgeInBounds = false; elemRect = $element[ 0 ].getBoundingClientRect(); if ( $container[ 0 ] === window ) { contRect = { top: 0, left: 0, right: document.documentElement.clientWidth, bottom: document.documentElement.clientHeight }; } else { contRect = $container[ 0 ].getBoundingClientRect(); } // For completeness, if we still cared about topEdgeInBounds, that'd be: // elemRect.top >= contRect.top && elemRect.top <= contRect.bottom if ( elemRect.left >= contRect.left && elemRect.left <= contRect.right ) { leftEdgeInBounds = true; } if ( elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom ) { bottomEdgeInBounds = true; } if ( elemRect.right >= contRect.left && elemRect.right <= contRect.right ) { rightEdgeInBounds = true; } // We only care that any part of the bottom edge is visible return bottomEdgeInBounds && ( leftEdgeInBounds || rightEdgeInBounds ); }; /** * Position the floatable below its container. * * This should only be done when both of them are attached to the DOM and visible. * * @chainable */ OO.ui.mixin.FloatableElement.prototype.position = function () { var pos; if ( !this.positioning ) { return this; } if ( !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable ) ) { this.$floatable.addClass( 'oo-ui-element-hidden' ); return; } else { this.$floatable.removeClass( 'oo-ui-element-hidden' ); } if ( !this.needsCustomPosition ) { return; } pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() ); // Position under container pos.top += this.$floatableContainer.height(); // In LTR, we position from the left, and pos.left is already set // In RTL, we position from the right instead. if ( this.$floatableContainer.css( 'direction' ) === 'rtl' ) { pos.right = this.$floatable.offsetParent().width() - pos.left - this.$floatableContainer.outerWidth(); delete pos.left; } this.$floatable.css( pos ); // We updated the position, so re-evaluate the clipping state. // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so // will not notice the need to update itself.) // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does // it not listen to the right events in the right places? if ( this.clip ) { this.clip(); } return this; }; /** * Element that can be automatically clipped to visible boundaries. * * Whenever the element's natural height changes, you have to call * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still * clipping correctly. * * The dimensions of #$clippableContainer will be compared to the boundaries of the * nearest scrollable container. If #$clippableContainer is too tall and/or too wide, * then #$clippable will be given a fixed reduced height and/or width and will be made * scrollable. By default, #$clippable and #$clippableContainer are the same element, * but you can build a static footer by setting #$clippableContainer to an element that contains * #$clippable and the footer. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer, * omit to use #$clippable */ OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) { // Configuration initialization config = config || {}; // Properties this.$clippable = null; this.$clippableContainer = null; this.clipping = false; this.clippedHorizontally = false; this.clippedVertically = false; this.$clippableScrollableContainer = null; this.$clippableScroller = null; this.$clippableWindow = null; this.idealWidth = null; this.idealHeight = null; this.onClippableScrollHandler = this.clip.bind( this ); this.onClippableWindowResizeHandler = this.clip.bind( this ); // Initialization if ( config.$clippableContainer ) { this.setClippableContainer( config.$clippableContainer ); } this.setClippableElement( config.$clippable || this.$element ); }; /* Methods */ /** * Set clippable element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $clippable Element to make clippable */ OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) { if ( this.$clippable ) { this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' ); this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } ); OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] ); } this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' ); this.clip(); }; /** * Set clippable container. * * This is the container that will be measured when deciding whether to clip. When clipping, * #$clippable will be resized in order to keep the clippable container fully visible. * * If the clippable container is unset, #$clippable will be used. * * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset */ OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) { this.$clippableContainer = $clippableContainer; if ( this.$clippable ) { this.clip(); } }; /** * Toggle clipping. * * Do not turn clipping on until after the element is attached to the DOM and visible. * * @param {boolean} [clipping] Enable clipping, omit to toggle * @chainable */ OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) { clipping = clipping === undefined ? !this.clipping : !!clipping; if ( clipping && !this.warnedUnattached && !this.isElementAttached() ) { OO.ui.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' ); this.warnedUnattached = true; } if ( this.clipping !== clipping ) { this.clipping = clipping; if ( clipping ) { this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() ); // If the clippable container is the root, we have to listen to scroll events and check // jQuery.scrollTop on the window because of browser inconsistencies this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ? $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) : this.$clippableScrollableContainer; this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler ); this.$clippableWindow = $( this.getElementWindow() ) .on( 'resize', this.onClippableWindowResizeHandler ); // Initial clip after visible this.clip(); } else { this.$clippable.css( { width: '', height: '', maxWidth: '', maxHeight: '', overflowX: '', overflowY: '' } ); OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] ); this.$clippableScrollableContainer = null; this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler ); this.$clippableScroller = null; this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler ); this.$clippableWindow = null; } } return this; }; /** * Check if the element will be clipped to fit the visible area of the nearest scrollable container. * * @return {boolean} Element will be clipped to the visible area */ OO.ui.mixin.ClippableElement.prototype.isClipping = function () { return this.clipping; }; /** * Check if the bottom or right of the element is being clipped by the nearest scrollable container. * * @return {boolean} Part of the element is being clipped */ OO.ui.mixin.ClippableElement.prototype.isClipped = function () { return this.clippedHorizontally || this.clippedVertically; }; /** * Check if the right of the element is being clipped by the nearest scrollable container. * * @return {boolean} Part of the element is being clipped */ OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () { return this.clippedHorizontally; }; /** * Check if the bottom of the element is being clipped by the nearest scrollable container. * * @return {boolean} Part of the element is being clipped */ OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () { return this.clippedVertically; }; /** * Set the ideal size. These are the dimensions the element will have when it's not being clipped. * * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix */ OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) { this.idealWidth = width; this.idealHeight = height; if ( !this.clipping ) { // Update dimensions this.$clippable.css( { width: width, height: height } ); } // While clipping, idealWidth and idealHeight are not considered }; /** * Clip element to visible boundaries and allow scrolling when needed. You should call this method * when the element's natural height changes. * * Element will be clipped the bottom or right of the element is within 10px of the edge of, or * overlapped by, the visible area of the nearest scrollable container. * * Because calling clip() when the natural height changes isn't always possible, we also set * max-height when the element isn't being clipped. This means that if the element tries to grow * beyond the edge, something reasonable will happen before clip() is called. * * @chainable */ OO.ui.mixin.ClippableElement.prototype.clip = function () { var $container, extraHeight, extraWidth, ccOffset, $scrollableContainer, scOffset, scHeight, scWidth, ccWidth, scrollerIsWindow, scrollTop, scrollLeft, desiredWidth, desiredHeight, allotedWidth, allotedHeight, naturalWidth, naturalHeight, clipWidth, clipHeight, buffer = 7; // Chosen by fair dice roll if ( !this.clipping ) { // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail return this; } $container = this.$clippableContainer || this.$clippable; extraHeight = $container.outerHeight() - this.$clippable.outerHeight(); extraWidth = $container.outerWidth() - this.$clippable.outerWidth(); ccOffset = $container.offset(); if ( this.$clippableScrollableContainer.is( 'html, body' ) ) { $scrollableContainer = this.$clippableWindow; scOffset = { top: 0, left: 0 }; } else { $scrollableContainer = this.$clippableScrollableContainer; scOffset = $scrollableContainer.offset(); } scHeight = $scrollableContainer.innerHeight() - buffer; scWidth = $scrollableContainer.innerWidth() - buffer; ccWidth = $container.outerWidth() + buffer; scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ]; scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0; scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0; desiredWidth = ccOffset.left < 0 ? ccWidth + ccOffset.left : ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left; desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top; // It should never be desirable to exceed the dimensions of the browser viewport... right? desiredWidth = Math.min( desiredWidth, document.documentElement.clientWidth ); desiredHeight = Math.min( desiredHeight, document.documentElement.clientHeight ); allotedWidth = Math.ceil( desiredWidth - extraWidth ); allotedHeight = Math.ceil( desiredHeight - extraHeight ); naturalWidth = this.$clippable.prop( 'scrollWidth' ); naturalHeight = this.$clippable.prop( 'scrollHeight' ); clipWidth = allotedWidth < naturalWidth; clipHeight = allotedHeight < naturalHeight; if ( clipWidth ) { // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672) // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case. this.$clippable.css( 'overflowX', 'scroll' ); void this.$clippable[ 0 ].offsetHeight; // Force reflow this.$clippable.css( { width: Math.max( 0, allotedWidth ), maxWidth: '' } ); } else { this.$clippable.css( { overflowX: '', width: this.idealWidth ? this.idealWidth - extraWidth : '', maxWidth: Math.max( 0, allotedWidth ) } ); } if ( clipHeight ) { // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672) // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case. this.$clippable.css( 'overflowY', 'scroll' ); void this.$clippable[ 0 ].offsetHeight; // Force reflow this.$clippable.css( { height: Math.max( 0, allotedHeight ), maxHeight: '' } ); } else { this.$clippable.css( { overflowY: '', height: this.idealHeight ? this.idealHeight - extraHeight : '', maxHeight: Math.max( 0, allotedHeight ) } ); } // If we stopped clipping in at least one of the dimensions if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) { OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] ); } this.clippedHorizontally = clipWidth; this.clippedVertically = clipHeight; return this; }; /** * PopupWidget is a container for content. The popup is overlaid and positioned absolutely. * By default, each popup has an anchor that points toward its origin. * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples. * * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle. * * @example * // A popup widget. * var popup = new OO.ui.PopupWidget( { * $content: $( '<p>Hi there!</p>' ), * padded: true, * width: 300 * } ); * * $( 'body' ).append( popup.$element ); * // To display the popup, toggle the visibility to 'true'. * popup.toggle( true ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.ClippableElement * @mixins OO.ui.mixin.FloatableElement * * @constructor * @param {Object} [config] Configuration options * @cfg {number} [width=320] Width of popup in pixels * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height. * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`. * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the * popup is leaning towards the right of the screen. * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence * in the given language, which means it will flip to the correct positioning in right-to-left languages. * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the * sentence in the given language. * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container. * See the [OOjs UI docs on MediaWiki][3] for an example. * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels. * @cfg {jQuery} [$content] Content to append to the popup's body * @cfg {jQuery} [$footer] Content to append to the popup's footer * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus. * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked. * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2] * for an example. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close * button. * @cfg {boolean} [padded=false] Add padding to the popup's body */ OO.ui.PopupWidget = function OoUiPopupWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.PopupWidget.parent.call( this, config ); // Properties (must be set before ClippableElement constructor call) this.$body = $( '<div>' ); this.$popup = $( '<div>' ); // Mixin constructors OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body, $clippableContainer: this.$popup } ) ); OO.ui.mixin.FloatableElement.call( this, config ); // Properties this.$anchor = $( '<div>' ); // If undefined, will be computed lazily in updateDimensions() this.$container = config.$container; this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10; this.autoClose = !!config.autoClose; this.$autoCloseIgnore = config.$autoCloseIgnore; this.transitionTimeout = null; this.anchor = null; this.width = config.width !== undefined ? config.width : 320; this.height = config.height !== undefined ? config.height : null; this.setAlignment( config.align ); this.onMouseDownHandler = this.onMouseDown.bind( this ); this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this ); // Initialization this.toggleAnchor( config.anchor === undefined || config.anchor ); this.$body.addClass( 'oo-ui-popupWidget-body' ); this.$anchor.addClass( 'oo-ui-popupWidget-anchor' ); this.$popup .addClass( 'oo-ui-popupWidget-popup' ) .append( this.$body ); this.$element .addClass( 'oo-ui-popupWidget' ) .append( this.$popup, this.$anchor ); // Move content, which was added to #$element by OO.ui.Widget, to the body // FIXME This is gross, we should use '$body' or something for the config if ( config.$content instanceof jQuery ) { this.$body.append( config.$content ); } if ( config.padded ) { this.$body.addClass( 'oo-ui-popupWidget-body-padded' ); } if ( config.head ) { this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } ); this.closeButton.connect( this, { click: 'onCloseButtonClick' } ); this.$head = $( '<div>' ) .addClass( 'oo-ui-popupWidget-head' ) .append( this.$label, this.closeButton.$element ); this.$popup.prepend( this.$head ); } if ( config.$footer ) { this.$footer = $( '<div>' ) .addClass( 'oo-ui-popupWidget-footer' ) .append( config.$footer ); this.$popup.append( this.$footer ); } // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods // that reference properties not initialized at that time of parent class construction // TODO: Find a better way to handle post-constructor setup this.visible = false; this.$element.addClass( 'oo-ui-element-hidden' ); }; /* Setup */ OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement ); OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.FloatableElement ); /* Methods */ /** * Handles mouse down events. * * @private * @param {MouseEvent} e Mouse down event */ OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) { if ( this.isVisible() && !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true ) ) { this.toggle( false ); } }; /** * Bind mouse down listener. * * @private */ OO.ui.PopupWidget.prototype.bindMouseDownListener = function () { // Capture clicks outside popup this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true ); }; /** * Handles close button click events. * * @private */ OO.ui.PopupWidget.prototype.onCloseButtonClick = function () { if ( this.isVisible() ) { this.toggle( false ); } }; /** * Unbind mouse down listener. * * @private */ OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () { this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true ); }; /** * Handles key down events. * * @private * @param {KeyboardEvent} e Key down event */ OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) { if ( e.which === OO.ui.Keys.ESCAPE && this.isVisible() ) { this.toggle( false ); e.preventDefault(); e.stopPropagation(); } }; /** * Bind key down listener. * * @private */ OO.ui.PopupWidget.prototype.bindKeyDownListener = function () { this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true ); }; /** * Unbind key down listener. * * @private */ OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () { this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true ); }; /** * Show, hide, or toggle the visibility of the anchor. * * @param {boolean} [show] Show anchor, omit to toggle */ OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) { show = show === undefined ? !this.anchored : !!show; if ( this.anchored !== show ) { if ( show ) { this.$element.addClass( 'oo-ui-popupWidget-anchored' ); } else { this.$element.removeClass( 'oo-ui-popupWidget-anchored' ); } this.anchored = show; } }; /** * Check if the anchor is visible. * * @return {boolean} Anchor is visible */ OO.ui.PopupWidget.prototype.hasAnchor = function () { return this.anchor; }; /** * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling * `.toggle( true )` after its #$element is attached to the DOM. * * Do not show the popup while it is not attached to the DOM. The calculations required to display * it in the right place and with the right dimensions only work correctly while it is attached. * Side-effects may include broken interface and exceptions being thrown. This wasn't always * strictly enforced, so currently it only generates a warning in the browser console. * * @inheritdoc */ OO.ui.PopupWidget.prototype.toggle = function ( show ) { var change; show = show === undefined ? !this.isVisible() : !!show; change = show !== this.isVisible(); if ( show && !this.warnedUnattached && !this.isElementAttached() ) { OO.ui.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' ); this.warnedUnattached = true; } // Parent method OO.ui.PopupWidget.parent.prototype.toggle.call( this, show ); if ( change ) { this.togglePositioning( show && !!this.$floatableContainer ); if ( show ) { if ( this.autoClose ) { this.bindMouseDownListener(); this.bindKeyDownListener(); } this.updateDimensions(); this.toggleClipping( true ); } else { this.toggleClipping( false ); if ( this.autoClose ) { this.unbindMouseDownListener(); this.unbindKeyDownListener(); } } } return this; }; /** * Set the size of the popup. * * Changing the size may also change the popup's position depending on the alignment. * * @param {number} width Width in pixels * @param {number} height Height in pixels * @param {boolean} [transition=false] Use a smooth transition * @chainable */ OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) { this.width = width; this.height = height !== undefined ? height : null; if ( this.isVisible() ) { this.updateDimensions( transition ); } }; /** * Update the size and position. * * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will * be called automatically. * * @param {boolean} [transition=false] Use a smooth transition * @chainable */ OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) { var popupOffset, originOffset, containerLeft, containerWidth, containerRight, popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth, direction, dirFactor, align, alignMap = { ltr: { 'force-left': 'backwards', 'force-right': 'forwards' }, rtl: { 'force-left': 'forwards', 'force-right': 'backwards' } }, widget = this; if ( !this.$container ) { // Lazy-initialize $container if not specified in constructor this.$container = $( this.getClosestScrollableElementContainer() ); } direction = this.$container.css( 'direction' ); dirFactor = direction === 'rtl' ? -1 : 1; align = alignMap[ direction ][ this.align ] || this.align; // Set height and width before measuring things, since it might cause our measurements // to change (e.g. due to scrollbars appearing or disappearing) this.$popup.css( { width: this.width, height: this.height !== null ? this.height : 'auto' } ); // Compute initial popupOffset based on alignment popupOffset = this.width * ( { backwards: -1, center: -0.5, forwards: 0 } )[ align ]; // Figure out if this will cause the popup to go beyond the edge of the container originOffset = this.$element.offset().left; containerLeft = this.$container.offset().left; containerWidth = this.$container.innerWidth(); containerRight = containerLeft + containerWidth; popupLeft = dirFactor * popupOffset - this.containerPadding; popupRight = dirFactor * popupOffset + this.containerPadding + this.width + this.containerPadding; overlapLeft = ( originOffset + popupLeft ) - containerLeft; overlapRight = containerRight - ( originOffset + popupRight ); // Adjust offset to make the popup not go beyond the edge, if needed if ( overlapRight < 0 ) { popupOffset += dirFactor * overlapRight; } else if ( overlapLeft < 0 ) { popupOffset -= dirFactor * overlapLeft; } // Adjust offset to avoid anchor being rendered too close to the edge // $anchor.width() doesn't work with the pure CSS anchor (returns 0) // TODO: Find a measurement that works for CSS anchors and image anchors anchorWidth = this.$anchor[ 0 ].scrollWidth * 2; if ( popupOffset + this.width < anchorWidth ) { popupOffset = anchorWidth - this.width; } else if ( -popupOffset < anchorWidth ) { popupOffset = -anchorWidth; } // Prevent transition from being interrupted clearTimeout( this.transitionTimeout ); if ( transition ) { // Enable transition this.$element.addClass( 'oo-ui-popupWidget-transitioning' ); } // Position body relative to anchor this.$popup.css( direction === 'rtl' ? 'margin-right' : 'margin-left', popupOffset ); if ( transition ) { // Prevent transitioning after transition is complete this.transitionTimeout = setTimeout( function () { widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' ); }, 200 ); } else { // Prevent transitioning immediately this.$element.removeClass( 'oo-ui-popupWidget-transitioning' ); } // Reevaluate clipping state since we've relocated and resized the popup this.clip(); return this; }; /** * Set popup alignment * * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`, * `backwards` or `forwards`. */ OO.ui.PopupWidget.prototype.setAlignment = function ( align ) { // Transform values deprecated since v0.11.0 if ( align === 'left' || align === 'right' ) { OO.ui.warnDeprecation( 'PopupWidget#setAlignment parameter value `' + align + '` is deprecated. Use `force-right` or `force-left` instead.' ); align = { left: 'force-right', right: 'force-left' }[ align ]; } // Validate alignment if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) { this.align = align; } else { this.align = 'center'; } }; /** * Get popup alignment * * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`, * `backwards` or `forwards`. */ OO.ui.PopupWidget.prototype.getAlignment = function () { return this.align; }; /** * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}. * A popup is a container for content. It is overlaid and positioned absolutely. By default, each * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin. * See {@link OO.ui.PopupWidget PopupWidget} for an example. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {Object} [popup] Configuration to pass to popup * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus */ OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) { // Configuration initialization config = config || {}; // Properties this.popup = new OO.ui.PopupWidget( $.extend( { autoClose: true }, config.popup, { $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore ) } ) ); }; /* Methods */ /** * Get popup. * * @return {OO.ui.PopupWidget} Popup widget */ OO.ui.mixin.PopupElement.prototype.getPopup = function () { return this.popup; }; /** * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget}, * which is used to display additional information or options. * * @example * // Example of a popup button. * var popupButton = new OO.ui.PopupButtonWidget( { * label: 'Popup button with options', * icon: 'menu', * popup: { * $content: $( '<p>Additional options here.</p>' ), * padded: true, * align: 'force-left' * } * } ); * // Append the button to the DOM. * $( 'body' ).append( popupButton.$element ); * * @class * @extends OO.ui.ButtonWidget * @mixins OO.ui.mixin.PopupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the * containing `<div>` and has a larger area. By default, the popup uses relative positioning. */ OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) { // Parent constructor OO.ui.PopupButtonWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.PopupElement.call( this, $.extend( true, {}, config, { popup: { $floatableContainer: this.$element } } ) ); // Properties this.$overlay = config.$overlay || this.$element; // Events this.connect( this, { click: 'onAction' } ); // Initialization this.$element .addClass( 'oo-ui-popupButtonWidget' ) .attr( 'aria-haspopup', 'true' ); this.popup.$element .addClass( 'oo-ui-popupButtonWidget-popup' ) .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() ) .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() ); this.$overlay.append( this.popup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget ); OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement ); /* Methods */ /** * Handle the button action being triggered. * * @private */ OO.ui.PopupButtonWidget.prototype.onAction = function () { this.popup.toggle(); }; /** * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement. * * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable. * * @private * @abstract * @class * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) { // Mixin constructors OO.ui.mixin.GroupElement.call( this, config ); }; /* Setup */ OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement ); /* Methods */ /** * Set the disabled state of the widget. * * This will also update the disabled state of child widgets. * * @param {boolean} disabled Disable widget * @chainable */ OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) { var i, len; // Parent method // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget OO.ui.Widget.prototype.setDisabled.call( this, disabled ); // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor if ( this.items ) { for ( i = 0, len = this.items.length; i < len; i++ ) { this.items[ i ].updateDisabled(); } } return this; }; /** * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget. * * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This * allows bidirectional communication. * * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable. * * @private * @abstract * @class * * @constructor */ OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() { // }; /* Methods */ /** * Check if widget is disabled. * * Checks parent if present, making disabled state inheritable. * * @return {boolean} Widget is disabled */ OO.ui.mixin.ItemWidget.prototype.isDisabled = function () { return this.disabled || ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() ); }; /** * Set group element is in. * * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none * @chainable */ OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) { // Parent method // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element OO.ui.Element.prototype.setElementGroup.call( this, group ); // Initialize item disabled states this.updateDisabled(); return this; }; /** * OptionWidgets are special elements that can be selected and configured with data. The * data is often unique for each option, but it does not have to be. OptionWidgets are used * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information * and examples, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.ItemWidget * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.AccessKeyedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.OptionWidget = function OoUiOptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.OptionWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ItemWidget.call( this ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.AccessKeyedElement.call( this, config ); // Properties this.selected = false; this.highlighted = false; this.pressed = false; // Initialization this.$element .data( 'oo-ui-optionWidget', this ) // Allow programmatic focussing (and by accesskey), but not tabbing .attr( 'tabindex', '-1' ) .attr( 'role', 'option' ) .attr( 'aria-selected', 'false' ) .addClass( 'oo-ui-optionWidget' ) .append( this.$label ); }; /* Setup */ OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement ); /* Static Properties */ /** * Whether this option can be selected. See #setSelected. * * @static * @inheritable * @property {boolean} */ OO.ui.OptionWidget.static.selectable = true; /** * Whether this option can be highlighted. See #setHighlighted. * * @static * @inheritable * @property {boolean} */ OO.ui.OptionWidget.static.highlightable = true; /** * Whether this option can be pressed. See #setPressed. * * @static * @inheritable * @property {boolean} */ OO.ui.OptionWidget.static.pressable = true; /** * Whether this option will be scrolled into view when it is selected. * * @static * @inheritable * @property {boolean} */ OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false; /* Methods */ /** * Check if the option can be selected. * * @return {boolean} Item is selectable */ OO.ui.OptionWidget.prototype.isSelectable = function () { return this.constructor.static.selectable && !this.isDisabled() && this.isVisible(); }; /** * Check if the option can be highlighted. A highlight indicates that the option * may be selected when a user presses enter or clicks. Disabled items cannot * be highlighted. * * @return {boolean} Item is highlightable */ OO.ui.OptionWidget.prototype.isHighlightable = function () { return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible(); }; /** * Check if the option can be pressed. The pressed state occurs when a user mouses * down on an item, but has not yet let go of the mouse. * * @return {boolean} Item is pressable */ OO.ui.OptionWidget.prototype.isPressable = function () { return this.constructor.static.pressable && !this.isDisabled() && this.isVisible(); }; /** * Check if the option is selected. * * @return {boolean} Item is selected */ OO.ui.OptionWidget.prototype.isSelected = function () { return this.selected; }; /** * Check if the option is highlighted. A highlight indicates that the * item may be selected when a user presses enter or clicks. * * @return {boolean} Item is highlighted */ OO.ui.OptionWidget.prototype.isHighlighted = function () { return this.highlighted; }; /** * Check if the option is pressed. The pressed state occurs when a user mouses * down on an item, but has not yet let go of the mouse. The item may appear * selected, but it will not be selected until the user releases the mouse. * * @return {boolean} Item is pressed */ OO.ui.OptionWidget.prototype.isPressed = function () { return this.pressed; }; /** * Set the option’s selected state. In general, all modifications to the selection * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Select option * @chainable */ OO.ui.OptionWidget.prototype.setSelected = function ( state ) { if ( this.constructor.static.selectable ) { this.selected = !!state; this.$element .toggleClass( 'oo-ui-optionWidget-selected', state ) .attr( 'aria-selected', state.toString() ); if ( state && this.constructor.static.scrollIntoViewOnSelect ) { this.scrollElementIntoView(); } this.updateThemeClasses(); } return this; }; /** * Set the option’s highlighted state. In general, all programmatic * modifications to the highlight should be handled by the * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Highlight option * @chainable */ OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) { if ( this.constructor.static.highlightable ) { this.highlighted = !!state; this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state ); this.updateThemeClasses(); } return this; }; /** * Set the option’s pressed state. In general, all * programmatic modifications to the pressed state should be handled by the * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Press option * @chainable */ OO.ui.OptionWidget.prototype.setPressed = function ( state ) { if ( this.constructor.static.pressable ) { this.pressed = !!state; this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state ); this.updateThemeClasses(); } return this; }; /** * Get text to match search strings against. * * The default implementation returns the label text, but subclasses * can override this to provide more complex behavior. * * @return {string|boolean} String to match search string against */ OO.ui.OptionWidget.prototype.getMatchText = function () { var label = this.getLabel(); return typeof label === 'string' ? label : this.$label.text(); }; /** * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of * select widgets, including {@link OO.ui.ButtonSelectWidget button selects}, * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget * menu selects}. * * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more * information, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example of a select widget with three options * var select = new OO.ui.SelectWidget( { * items: [ * new OO.ui.OptionWidget( { * data: 'a', * label: 'Option One', * } ), * new OO.ui.OptionWidget( { * data: 'b', * label: 'Option Two', * } ), * new OO.ui.OptionWidget( { * data: 'c', * label: 'Option Three', * } ) * ] * } ); * $( 'body' ).append( select.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select. * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See * the [OOjs UI documentation on MediaWiki] [2] for examples. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options */ OO.ui.SelectWidget = function OoUiSelectWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.SelectWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Properties this.pressed = false; this.selecting = null; this.onMouseUpHandler = this.onMouseUp.bind( this ); this.onMouseMoveHandler = this.onMouseMove.bind( this ); this.onKeyDownHandler = this.onKeyDown.bind( this ); this.onKeyPressHandler = this.onKeyPress.bind( this ); this.keyPressBuffer = ''; this.keyPressBufferTimer = null; this.blockMouseOverEvents = 0; // Events this.connect( this, { toggle: 'onToggle' } ); this.$element.on( { focusin: this.onFocus.bind( this ), mousedown: this.onMouseDown.bind( this ), mouseover: this.onMouseOver.bind( this ), mouseleave: this.onMouseLeave.bind( this ) } ); // Initialization this.$element .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' ) .attr( 'role', 'listbox' ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget ); /* Events */ /** * @event highlight * * A `highlight` event is emitted when the highlight is changed with the #highlightItem method. * * @param {OO.ui.OptionWidget|null} item Highlighted item */ /** * @event press * * A `press` event is emitted when the #pressItem method is used to programmatically modify the * pressed state of an option. * * @param {OO.ui.OptionWidget|null} item Pressed item */ /** * @event select * * A `select` event is emitted when the selection is modified programmatically with the #selectItem method. * * @param {OO.ui.OptionWidget|null} item Selected item */ /** * @event choose * A `choose` event is emitted when an item is chosen with the #chooseItem method. * @param {OO.ui.OptionWidget} item Chosen item */ /** * @event add * * An `add` event is emitted when options are added to the select with the #addItems method. * * @param {OO.ui.OptionWidget[]} items Added items * @param {number} index Index of insertion point */ /** * @event remove * * A `remove` event is emitted when options are removed from the select with the #clearItems * or #removeItems methods. * * @param {OO.ui.OptionWidget[]} items Removed items */ /* Methods */ /** * Handle focus events * * @private * @param {jQuery.Event} event */ OO.ui.SelectWidget.prototype.onFocus = function ( event ) { var item; if ( event.target === this.$element[ 0 ] ) { // This widget was focussed, e.g. by the user tabbing to it. // The styles for focus state depend on one of the items being selected. if ( !this.getSelectedItem() ) { item = this.getFirstSelectableItem(); } } else { // One of the options got focussed (and the event bubbled up here). // They can't be tabbed to, but they can be activated using accesskeys. item = this.getTargetItem( event ); } if ( item ) { if ( item.constructor.static.highlightable ) { this.highlightItem( item ); } else { this.selectItem( item ); } } if ( event.target !== this.$element[ 0 ] ) { this.$element.focus(); } }; /** * Handle mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) { var item; if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) { this.togglePressed( true ); item = this.getTargetItem( e ); if ( item && item.isSelectable() ) { this.pressItem( item ); this.selecting = item; this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true ); this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true ); } } return false; }; /** * Handle mouse up events. * * @private * @param {MouseEvent} e Mouse up event */ OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) { var item; this.togglePressed( false ); if ( !this.selecting ) { item = this.getTargetItem( e ); if ( item && item.isSelectable() ) { this.selecting = item; } } if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) { this.pressItem( null ); this.chooseItem( this.selecting ); this.selecting = null; } this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true ); this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true ); return false; }; /** * Handle mouse move events. * * @private * @param {MouseEvent} e Mouse move event */ OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) { var item; if ( !this.isDisabled() && this.pressed ) { item = this.getTargetItem( e ); if ( item && item !== this.selecting && item.isSelectable() ) { this.pressItem( item ); this.selecting = item; } } }; /** * Handle mouse over events. * * @private * @param {jQuery.Event} e Mouse over event */ OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) { var item; if ( this.blockMouseOverEvents ) { return; } if ( !this.isDisabled() ) { item = this.getTargetItem( e ); this.highlightItem( item && item.isHighlightable() ? item : null ); } return false; }; /** * Handle mouse leave events. * * @private * @param {jQuery.Event} e Mouse over event */ OO.ui.SelectWidget.prototype.onMouseLeave = function () { if ( !this.isDisabled() ) { this.highlightItem( null ); } return false; }; /** * Handle key down events. * * @protected * @param {KeyboardEvent} e Key down event */ OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) { var nextItem, handled = false, currentItem = this.getHighlightedItem() || this.getSelectedItem(); if ( !this.isDisabled() && this.isVisible() ) { switch ( e.keyCode ) { case OO.ui.Keys.ENTER: if ( currentItem && currentItem.constructor.static.highlightable ) { // Was only highlighted, now let's select it. No-op if already selected. this.chooseItem( currentItem ); handled = true; } break; case OO.ui.Keys.UP: case OO.ui.Keys.LEFT: this.clearKeyPressBuffer(); nextItem = this.getRelativeSelectableItem( currentItem, -1 ); handled = true; break; case OO.ui.Keys.DOWN: case OO.ui.Keys.RIGHT: this.clearKeyPressBuffer(); nextItem = this.getRelativeSelectableItem( currentItem, 1 ); handled = true; break; case OO.ui.Keys.ESCAPE: case OO.ui.Keys.TAB: if ( currentItem && currentItem.constructor.static.highlightable ) { currentItem.setHighlighted( false ); } this.unbindKeyDownListener(); this.unbindKeyPressListener(); // Don't prevent tabbing away / defocusing handled = false; break; } if ( nextItem ) { if ( nextItem.constructor.static.highlightable ) { this.highlightItem( nextItem ); } else { this.chooseItem( nextItem ); } this.scrollItemIntoView( nextItem ); } if ( handled ) { e.preventDefault(); e.stopPropagation(); } } }; /** * Bind key down listener. * * @protected */ OO.ui.SelectWidget.prototype.bindKeyDownListener = function () { this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true ); }; /** * Unbind key down listener. * * @protected */ OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () { this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true ); }; /** * Scroll item into view, preventing spurious mouse highlight actions from happening. * * @param {OO.ui.OptionWidget} item Item to scroll into view */ OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) { var widget = this; // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling // and around 100-150 ms after it is finished. this.blockMouseOverEvents++; item.scrollElementIntoView().done( function () { setTimeout( function () { widget.blockMouseOverEvents--; }, 200 ); } ); }; /** * Clear the key-press buffer * * @protected */ OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () { if ( this.keyPressBufferTimer ) { clearTimeout( this.keyPressBufferTimer ); this.keyPressBufferTimer = null; } this.keyPressBuffer = ''; }; /** * Handle key press events. * * @protected * @param {KeyboardEvent} e Key press event */ OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) { var c, filter, item; if ( !e.charCode ) { if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) { this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 ); return false; } return; } if ( String.fromCodePoint ) { c = String.fromCodePoint( e.charCode ); } else { c = String.fromCharCode( e.charCode ); } if ( this.keyPressBufferTimer ) { clearTimeout( this.keyPressBufferTimer ); } this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 ); item = this.getHighlightedItem() || this.getSelectedItem(); if ( this.keyPressBuffer === c ) { // Common (if weird) special case: typing "xxxx" will cycle through all // the items beginning with "x". if ( item ) { item = this.getRelativeSelectableItem( item, 1 ); } } else { this.keyPressBuffer += c; } filter = this.getItemMatcher( this.keyPressBuffer, false ); if ( !item || !filter( item ) ) { item = this.getRelativeSelectableItem( item, 1, filter ); } if ( item ) { if ( this.isVisible() && item.constructor.static.highlightable ) { this.highlightItem( item ); } else { this.chooseItem( item ); } this.scrollItemIntoView( item ); } e.preventDefault(); e.stopPropagation(); }; /** * Get a matcher for the specific string * * @protected * @param {string} s String to match against items * @param {boolean} [exact=false] Only accept exact matches * @return {Function} function ( OO.ui.OptionWidget ) => boolean */ OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) { var re; if ( s.normalize ) { s = s.normalize(); } s = exact ? s.trim() : s.replace( /^\s+/, '' ); re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' ); if ( exact ) { re += '\\s*$'; } re = new RegExp( re, 'i' ); return function ( item ) { var matchText = item.getMatchText(); if ( matchText.normalize ) { matchText = matchText.normalize(); } return re.test( matchText ); }; }; /** * Bind key press listener. * * @protected */ OO.ui.SelectWidget.prototype.bindKeyPressListener = function () { this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true ); }; /** * Unbind key down listener. * * If you override this, be sure to call this.clearKeyPressBuffer() from your * implementation. * * @protected */ OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () { this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true ); this.clearKeyPressBuffer(); }; /** * Visibility change handler * * @protected * @param {boolean} visible */ OO.ui.SelectWidget.prototype.onToggle = function ( visible ) { if ( !visible ) { this.clearKeyPressBuffer(); } }; /** * Get the closest item to a jQuery.Event. * * @private * @param {jQuery.Event} e * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found */ OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) { return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null; }; /** * Get selected item. * * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected */ OO.ui.SelectWidget.prototype.getSelectedItem = function () { var i, len; for ( i = 0, len = this.items.length; i < len; i++ ) { if ( this.items[ i ].isSelected() ) { return this.items[ i ]; } } return null; }; /** * Get highlighted item. * * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted */ OO.ui.SelectWidget.prototype.getHighlightedItem = function () { var i, len; for ( i = 0, len = this.items.length; i < len; i++ ) { if ( this.items[ i ].isHighlighted() ) { return this.items[ i ]; } } return null; }; /** * Toggle pressed state. * * Press is a state that occurs when a user mouses down on an item, but * has not yet let go of the mouse. The item may appear selected, but it will not be selected * until the user releases the mouse. * * @param {boolean} pressed An option is being pressed */ OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) { if ( pressed === undefined ) { pressed = !this.pressed; } if ( pressed !== this.pressed ) { this.$element .toggleClass( 'oo-ui-selectWidget-pressed', pressed ) .toggleClass( 'oo-ui-selectWidget-depressed', !pressed ); this.pressed = pressed; } }; /** * Highlight an option. If the `item` param is omitted, no options will be highlighted * and any existing highlight will be removed. The highlight is mutually exclusive. * * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight * @fires highlight * @chainable */ OO.ui.SelectWidget.prototype.highlightItem = function ( item ) { var i, len, highlighted, changed = false; for ( i = 0, len = this.items.length; i < len; i++ ) { highlighted = this.items[ i ] === item; if ( this.items[ i ].isHighlighted() !== highlighted ) { this.items[ i ].setHighlighted( highlighted ); changed = true; } } if ( changed ) { this.emit( 'highlight', item ); } return this; }; /** * Fetch an item by its label. * * @param {string} label Label of the item to select. * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists */ OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) { var i, item, found, len = this.items.length, filter = this.getItemMatcher( label, true ); for ( i = 0; i < len; i++ ) { item = this.items[ i ]; if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) { return item; } } if ( prefix ) { found = null; filter = this.getItemMatcher( label, false ); for ( i = 0; i < len; i++ ) { item = this.items[ i ]; if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) { if ( found ) { return null; } found = item; } } if ( found ) { return found; } } return null; }; /** * Programmatically select an option by its label. If the item does not exist, * all options will be deselected. * * @param {string} [label] Label of the item to select. * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches * @fires select * @chainable */ OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) { var itemFromLabel = this.getItemFromLabel( label, !!prefix ); if ( label === undefined || !itemFromLabel ) { return this.selectItem(); } return this.selectItem( itemFromLabel ); }; /** * Programmatically select an option by its data. If the `data` parameter is omitted, * or if the item does not exist, all options will be deselected. * * @param {Object|string} [data] Value of the item to select, omit to deselect all * @fires select * @chainable */ OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) { var itemFromData = this.getItemFromData( data ); if ( data === undefined || !itemFromData ) { return this.selectItem(); } return this.selectItem( itemFromData ); }; /** * Programmatically select an option by its reference. If the `item` parameter is omitted, * all options will be deselected. * * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all * @fires select * @chainable */ OO.ui.SelectWidget.prototype.selectItem = function ( item ) { var i, len, selected, changed = false; for ( i = 0, len = this.items.length; i < len; i++ ) { selected = this.items[ i ] === item; if ( this.items[ i ].isSelected() !== selected ) { this.items[ i ].setSelected( selected ); changed = true; } } if ( changed ) { this.emit( 'select', item ); } return this; }; /** * Press an item. * * Press is a state that occurs when a user mouses down on an item, but has not * yet let go of the mouse. The item may appear selected, but it will not be selected until the user * releases the mouse. * * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all * @fires press * @chainable */ OO.ui.SelectWidget.prototype.pressItem = function ( item ) { var i, len, pressed, changed = false; for ( i = 0, len = this.items.length; i < len; i++ ) { pressed = this.items[ i ] === item; if ( this.items[ i ].isPressed() !== pressed ) { this.items[ i ].setPressed( pressed ); changed = true; } } if ( changed ) { this.emit( 'press', item ); } return this; }; /** * Choose an item. * * Note that ‘choose’ should never be modified programmatically. A user can choose * an option with the keyboard or mouse and it becomes selected. To select an item programmatically, * use the #selectItem method. * * This method is identical to #selectItem, but may vary in subclasses that take additional action * when users choose an item with the keyboard or mouse. * * @param {OO.ui.OptionWidget} item Item to choose * @fires choose * @chainable */ OO.ui.SelectWidget.prototype.chooseItem = function ( item ) { if ( item ) { this.selectItem( item ); this.emit( 'choose', item ); } return this; }; /** * Get an option by its position relative to the specified item (or to the start of the option array, * if item is `null`). The direction in which to search through the option array is specified with a * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or * `null` if there are no options in the array. * * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array. * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward * @param {Function} [filter] Only consider items for which this function returns * true. Function takes an OO.ui.OptionWidget and returns a boolean. * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select */ OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) { var currentIndex, nextIndex, i, increase = direction > 0 ? 1 : -1, len = this.items.length; if ( item instanceof OO.ui.OptionWidget ) { currentIndex = this.items.indexOf( item ); nextIndex = ( currentIndex + increase + len ) % len; } else { // If no item is selected and moving forward, start at the beginning. // If moving backward, start at the end. nextIndex = direction > 0 ? 0 : len - 1; } for ( i = 0; i < len; i++ ) { item = this.items[ nextIndex ]; if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && ( !filter || filter( item ) ) ) { return item; } nextIndex = ( nextIndex + increase + len ) % len; } return null; }; /** * Get the next selectable item or `null` if there are no selectable items. * Disabled options and menu-section markers and breaks are not selectable. * * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items */ OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () { return this.getRelativeSelectableItem( null, 1 ); }; /** * Add an array of options to the select. Optionally, an index number can be used to * specify an insertion point. * * @param {OO.ui.OptionWidget[]} items Items to add * @param {number} [index] Index to insert items after * @fires add * @chainable */ OO.ui.SelectWidget.prototype.addItems = function ( items, index ) { // Mixin method OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index ); // Always provide an index, even if it was omitted this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index ); return this; }; /** * Remove the specified array of options from the select. Options will be detached * from the DOM, not removed, so they can be reused later. To remove all options from * the select, you may wish to use the #clearItems method instead. * * @param {OO.ui.OptionWidget[]} items Items to remove * @fires remove * @chainable */ OO.ui.SelectWidget.prototype.removeItems = function ( items ) { var i, len, item; // Deselect items being removed for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; if ( item.isSelected() ) { this.selectItem( null ); } } // Mixin method OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items ); this.emit( 'remove', items ); return this; }; /** * Clear all options from the select. Options will be detached from the DOM, not removed, * so that they can be reused later. To remove a subset of options from the select, use * the #removeItems method. * * @fires remove * @chainable */ OO.ui.SelectWidget.prototype.clearItems = function () { var items = this.items.slice(); // Mixin method OO.ui.mixin.GroupWidget.prototype.clearItems.call( this ); // Clear selection this.selectItem( null ); this.emit( 'remove', items ); return this; }; /** * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}. * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive * options. For more information about options and selects, please see the * [OOjs UI documentation on MediaWiki][1]. * * @example * // Decorated options in a select widget * var select = new OO.ui.SelectWidget( { * items: [ * new OO.ui.DecoratedOptionWidget( { * data: 'a', * label: 'Option with icon', * icon: 'help' * } ), * new OO.ui.DecoratedOptionWidget( { * data: 'b', * label: 'Option with indicator', * indicator: 'next' * } ) * ] * } ); * $( 'body' ).append( select.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.OptionWidget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) { // Parent constructor OO.ui.DecoratedOptionWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-decoratedOptionWidget' ) .prepend( this.$icon ) .append( this.$indicator ); }; /* Setup */ OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget ); OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement ); /** * MenuOptionWidget is an option widget that looks like a menu item. The class is used with * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see * the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.DecoratedOptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) { // Configuration initialization config = $.extend( { icon: 'check' }, config ); // Parent constructor OO.ui.MenuOptionWidget.parent.call( this, config ); // Initialization this.$element .attr( 'role', 'menuitem' ) .addClass( 'oo-ui-menuOptionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true; /** * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected. * * @example * var myDropdown = new OO.ui.DropdownWidget( { * menu: { * items: [ * new OO.ui.MenuSectionOptionWidget( { * label: 'Dogs' * } ), * new OO.ui.MenuOptionWidget( { * data: 'corgi', * label: 'Welsh Corgi' * } ), * new OO.ui.MenuOptionWidget( { * data: 'poodle', * label: 'Standard Poodle' * } ), * new OO.ui.MenuSectionOptionWidget( { * label: 'Cats' * } ), * new OO.ui.MenuOptionWidget( { * data: 'lion', * label: 'Lion' * } ) * ] * } * } ); * $( 'body' ).append( myDropdown.$element ); * * @class * @extends OO.ui.DecoratedOptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) { // Parent constructor OO.ui.MenuSectionOptionWidget.parent.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-menuSectionOptionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.MenuSectionOptionWidget.static.selectable = false; /** * @static * @inheritdoc */ OO.ui.MenuSectionOptionWidget.static.highlightable = false; /** * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget. * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}, * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus. * MenuSelectWidgets themselves are not instantiated directly, rather subclassed * and customized to be opened, closed, and displayed as needed. * * By default, menus are clipped to the visible viewport and are not visible when a user presses the * mouse outside the menu. * * Menus also have support for keyboard interaction: * * - Enter/Return key: choose and select a menu option * - Up-arrow key: highlight the previous menu option * - Down-arrow key: highlight the next menu option * - Esc key: hide the menu * * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle. * * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.mixin.ClippableElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget} * and {@link OO.ui.mixin.LookupElement LookupElement} * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget} * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks * that button, unless the button (or its parent widget) is passed in here. * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu. * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option. * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input */ OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.MenuSelectWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) ); // Properties this.autoHide = config.autoHide === undefined || !!config.autoHide; this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose; this.filterFromInput = !!config.filterFromInput; this.$input = config.$input ? config.$input : config.input ? config.input.$input : null; this.$widget = config.widget ? config.widget.$element : null; this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this ); this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 ); // Initialization this.$element .addClass( 'oo-ui-menuSelectWidget' ) .attr( 'role', 'menu' ); // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods // that reference properties not initialized at that time of parent class construction // TODO: Find a better way to handle post-constructor setup this.visible = false; this.$element.addClass( 'oo-ui-element-hidden' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement ); /* Methods */ /** * Handles document mouse down events. * * @protected * @param {MouseEvent} e Mouse down event */ OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) { if ( !OO.ui.contains( this.$element[ 0 ], e.target, true ) && ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) ) ) { this.toggle( false ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) { var currentItem = this.getHighlightedItem() || this.getSelectedItem(); if ( !this.isDisabled() && this.isVisible() ) { switch ( e.keyCode ) { case OO.ui.Keys.LEFT: case OO.ui.Keys.RIGHT: // Do nothing if a text field is associated, arrow keys will be handled natively if ( !this.$input ) { OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e ); } break; case OO.ui.Keys.ESCAPE: case OO.ui.Keys.TAB: if ( currentItem ) { currentItem.setHighlighted( false ); } this.toggle( false ); // Don't prevent tabbing away, prevent defocusing if ( e.keyCode === OO.ui.Keys.ESCAPE ) { e.preventDefault(); e.stopPropagation(); } break; default: OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e ); return; } } }; /** * Update menu item visibility after input changes. * * @protected */ OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () { var i, item, visible, anyVisible = false, len = this.items.length, showAll = !this.isVisible(), filter = showAll ? null : this.getItemMatcher( this.$input.val() ); for ( i = 0; i < len; i++ ) { item = this.items[ i ]; if ( item instanceof OO.ui.OptionWidget ) { visible = showAll || filter( item ); anyVisible = anyVisible || visible; item.toggle( visible ); } } this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible ); // Reevaluate clipping this.clip(); }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () { if ( this.$input ) { this.$input.on( 'keydown', this.onKeyDownHandler ); } else { OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () { if ( this.$input ) { this.$input.off( 'keydown', this.onKeyDownHandler ); } else { OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () { if ( this.$input ) { if ( this.filterFromInput ) { this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler ); } } else { OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () { if ( this.$input ) { if ( this.filterFromInput ) { this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler ); this.updateItemVisibility(); } } else { OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this ); } }; /** * Choose an item. * * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false. * * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method. * * @param {OO.ui.OptionWidget} item Item to choose * @chainable */ OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) { OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item ); if ( this.hideOnChoose ) { this.toggle( false ); } return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) { // Parent method OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index ); // Reevaluate clipping this.clip(); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) { // Parent method OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items ); // Reevaluate clipping this.clip(); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.clearItems = function () { // Parent method OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this ); // Reevaluate clipping this.clip(); return this; }; /** * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling * `.toggle( true )` after its #$element is attached to the DOM. * * Do not show the menu while it is not attached to the DOM. The calculations required to display * it in the right place and with the right dimensions only work correctly while it is attached. * Side-effects may include broken interface and exceptions being thrown. This wasn't always * strictly enforced, so currently it only generates a warning in the browser console. * * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) { var change; visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length; change = visible !== this.isVisible(); if ( visible && !this.warnedUnattached && !this.isElementAttached() ) { OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' ); this.warnedUnattached = true; } // Parent method OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible ); if ( change ) { if ( visible ) { this.bindKeyDownListener(); this.bindKeyPressListener(); this.toggleClipping( true ); if ( this.getSelectedItem() ) { this.getSelectedItem().scrollElementIntoView( { duration: 0 } ); } // Auto-hide if ( this.autoHide ) { this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true ); } } else { this.unbindKeyDownListener(); this.unbindKeyPressListener(); this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true ); this.toggleClipping( false ); } } return this; }; /** * DropdownWidgets are not menus themselves, rather they contain a menu of options created with * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that * users can interact with it. * * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use * OO.ui.DropdownInputWidget instead. * * @example * // Example: A DropdownWidget with a menu that contains three options * var dropDown = new OO.ui.DropdownWidget( { * label: 'Dropdown menu: Select a menu option', * menu: { * items: [ * new OO.ui.MenuOptionWidget( { * data: 'a', * label: 'First' * } ), * new OO.ui.MenuOptionWidget( { * data: 'b', * label: 'Second' * } ), * new OO.ui.MenuOptionWidget( { * data: 'c', * label: 'Third' * } ) * ] * } * } ); * * $( 'body' ).append( dropDown.$element ); * * dropDown.getMenu().selectItemByData( 'b' ); * * dropDown.getMenu().getSelectedItem().getData(); // returns 'b' * * For more information, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget} * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the * containing `<div>` and has a larger area. By default, the menu uses relative positioning. */ OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) { // Configuration initialization config = $.extend( { indicator: 'down' }, config ); // Parent constructor OO.ui.DropdownWidget.parent.call( this, config ); // Properties (must be set before TabIndexedElement constructor call) this.$handle = this.$( '<span>' ); this.$overlay = config.$overlay || this.$element; // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) ); // Properties this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( { widget: this, $container: this.$element }, config.menu ) ); // Events this.$handle.on( { click: this.onClick.bind( this ), keydown: this.onKeyDown.bind( this ), // Hack? Handle type-to-search when menu is not expanded and not handling its own events keypress: this.menu.onKeyPressHandler, blur: this.menu.clearKeyPressBuffer.bind( this.menu ) } ); this.menu.connect( this, { select: 'onMenuSelect', toggle: 'onMenuToggle' } ); // Initialization this.$handle .addClass( 'oo-ui-dropdownWidget-handle' ) .append( this.$icon, this.$label, this.$indicator ); this.$element .addClass( 'oo-ui-dropdownWidget' ) .append( this.$handle ); this.$overlay.append( this.menu.$element ); }; /* Setup */ OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * Get the menu. * * @return {OO.ui.MenuSelectWidget} Menu of widget */ OO.ui.DropdownWidget.prototype.getMenu = function () { return this.menu; }; /** * Handles menu select events. * * @private * @param {OO.ui.MenuOptionWidget} item Selected menu item */ OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) { var selectedLabel; if ( !item ) { this.setLabel( null ); return; } selectedLabel = item.getLabel(); // If the label is a DOM element, clone it, because setLabel will append() it if ( selectedLabel instanceof jQuery ) { selectedLabel = selectedLabel.clone(); } this.setLabel( selectedLabel ); }; /** * Handle menu toggle events. * * @private * @param {boolean} isVisible Menu toggle event */ OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) { this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible ); }; /** * Handle mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.DropdownWidget.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) { this.menu.toggle(); } return false; }; /** * Handle key down events. * * @private * @param {jQuery.Event} e Key down event */ OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.ENTER || ( !this.menu.isVisible() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.UP || e.which === OO.ui.Keys.DOWN ) ) ) ) { this.menu.toggle(); return false; } }; /** * RadioOptionWidget is an option widget that looks like a radio button. * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option * * @class * @extends OO.ui.OptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } ); // Parent constructor OO.ui.RadioOptionWidget.parent.call( this, config ); // Initialization // Remove implicit role, we're handling it ourselves this.radio.$input.attr( 'role', 'presentation' ); this.$element .addClass( 'oo-ui-radioOptionWidget' ) .attr( 'role', 'radio' ) .attr( 'aria-checked', 'false' ) .removeAttr( 'aria-selected' ) .prepend( this.radio.$element ); }; /* Setup */ OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.RadioOptionWidget.static.highlightable = false; /** * @static * @inheritdoc */ OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true; /** * @static * @inheritdoc */ OO.ui.RadioOptionWidget.static.pressable = false; /** * @static * @inheritdoc */ OO.ui.RadioOptionWidget.static.tagName = 'label'; /* Methods */ /** * @inheritdoc */ OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) { OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state ); this.radio.setSelected( state ); this.$element .attr( 'aria-checked', state.toString() ) .removeAttr( 'aria-selected' ); return this; }; /** * @inheritdoc */ OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) { OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled ); this.radio.setDisabled( this.isDisabled() ); return this; }; /** * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides * an interface for adding, removing and selecting options. * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use * OO.ui.RadioSelectInputWidget instead. * * @example * // A RadioSelectWidget with RadioOptions. * var option1 = new OO.ui.RadioOptionWidget( { * data: 'a', * label: 'Selected radio option' * } ); * * var option2 = new OO.ui.RadioOptionWidget( { * data: 'b', * label: 'Unselected radio option' * } ); * * var radioSelect=new OO.ui.RadioSelectWidget( { * items: [ option1, option2 ] * } ); * * // Select 'option 1' using the RadioSelectWidget's selectItem() method. * radioSelect.selectItem( option1 ); * * $( 'body' ).append( radioSelect.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) { // Parent constructor OO.ui.RadioSelectWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.TabIndexedElement.call( this, config ); // Events this.$element.on( { focus: this.bindKeyDownListener.bind( this ), blur: this.unbindKeyDownListener.bind( this ) } ); // Initialization this.$element .addClass( 'oo-ui-radioSelectWidget' ) .attr( 'role', 'radiogroup' ); }; /* Setup */ OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement ); /** * MultioptionWidgets are special elements that can be selected and configured with data. The * data is often unique for each option, but it does not have to be. MultioptionWidgets are used * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information * and examples, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.ItemWidget * @mixins OO.ui.mixin.LabelElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [selected=false] Whether the option is initially selected */ OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.MultioptionWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ItemWidget.call( this ); OO.ui.mixin.LabelElement.call( this, config ); // Properties this.selected = null; // Initialization this.$element .addClass( 'oo-ui-multioptionWidget' ) .append( this.$label ); this.setSelected( config.selected ); }; /* Setup */ OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget ); OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement ); /* Events */ /** * @event change * * A change event is emitted when the selected state of the option changes. * * @param {boolean} selected Whether the option is now selected */ /* Methods */ /** * Check if the option is selected. * * @return {boolean} Item is selected */ OO.ui.MultioptionWidget.prototype.isSelected = function () { return this.selected; }; /** * Set the option’s selected state. In general, all modifications to the selection * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Select option * @chainable */ OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) { state = !!state; if ( this.selected !== state ) { this.selected = state; this.emit( 'change', state ); this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state ); } return this; }; /** * MultiselectWidget allows selecting multiple options from a list. * * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @abstract * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect. */ OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) { // Parent constructor OO.ui.MultiselectWidget.parent.call( this, config ); // Configuration initialization config = config || {}; // Mixin constructors OO.ui.mixin.GroupWidget.call( this, config ); // Events this.aggregate( { change: 'select' } ); // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted // by GroupElement only when items are added/removed this.connect( this, { select: [ 'emit', 'change' ] } ); // Initialization if ( config.items ) { this.addItems( config.items ); } this.$group.addClass( 'oo-ui-multiselectWidget-group' ); this.$element.addClass( 'oo-ui-multiselectWidget' ) .append( this.$group ); }; /* Setup */ OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget ); /* Events */ /** * @event change * * A change event is emitted when the set of items changes, or an item is selected or deselected. */ /** * @event select * * A select event is emitted when an item is selected or deselected. */ /* Methods */ /** * Get options that are selected. * * @return {OO.ui.MultioptionWidget[]} Selected options */ OO.ui.MultiselectWidget.prototype.getSelectedItems = function () { return this.items.filter( function ( item ) { return item.isSelected(); } ); }; /** * Get the data of options that are selected. * * @return {Object[]|string[]} Values of selected options */ OO.ui.MultiselectWidget.prototype.getSelectedItemsData = function () { return this.getSelectedItems().map( function ( item ) { return item.data; } ); }; /** * Select options by reference. Options not mentioned in the `items` array will be deselected. * * @param {OO.ui.MultioptionWidget[]} items Items to select * @chainable */ OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) { this.items.forEach( function ( item ) { var selected = items.indexOf( item ) !== -1; item.setSelected( selected ); } ); return this; }; /** * Select items by their data. Options not mentioned in the `datas` array will be deselected. * * @param {Object[]|string[]} datas Values of items to select * @chainable */ OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) { var items, widget = this; items = datas.map( function ( data ) { return widget.getItemFromData( data ); } ); this.selectItems( items ); return this; }; /** * CheckboxMultioptionWidget is an option widget that looks like a checkbox. * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option * * @class * @extends OO.ui.MultioptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.checkbox = new OO.ui.CheckboxInputWidget(); // Parent constructor OO.ui.CheckboxMultioptionWidget.parent.call( this, config ); // Events this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) ); this.$element.on( 'keydown', this.onKeyDown.bind( this ) ); // Initialization this.$element .addClass( 'oo-ui-checkboxMultioptionWidget' ) .prepend( this.checkbox.$element ); }; /* Setup */ OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.CheckboxMultioptionWidget.static.tagName = 'label'; /* Methods */ /** * Handle checkbox selected state change. * * @private */ OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () { this.setSelected( this.checkbox.isSelected() ); }; /** * @inheritdoc */ OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) { OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state ); this.checkbox.setSelected( state ); return this; }; /** * @inheritdoc */ OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) { OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled ); this.checkbox.setDisabled( this.isDisabled() ); return this; }; /** * Focus the widget. */ OO.ui.CheckboxMultioptionWidget.prototype.focus = function () { this.checkbox.focus(); }; /** * Handle key down events. * * @protected * @param {jQuery.Event} e */ OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) { var element = this.getElementGroup(), nextItem; if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) { nextItem = element.getRelativeFocusableItem( this, -1 ); } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) { nextItem = element.getRelativeFocusableItem( this, 1 ); } if ( nextItem ) { e.preventDefault(); nextItem.focus(); } }; /** * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options. * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use * OO.ui.CheckboxMultiselectInputWidget instead. * * @example * // A CheckboxMultiselectWidget with CheckboxMultioptions. * var option1 = new OO.ui.CheckboxMultioptionWidget( { * data: 'a', * selected: true, * label: 'Selected checkbox' * } ); * * var option2 = new OO.ui.CheckboxMultioptionWidget( { * data: 'b', * label: 'Unselected checkbox' * } ); * * var multiselect=new OO.ui.CheckboxMultiselectWidget( { * items: [ option1, option2 ] * } ); * * $( 'body' ).append( multiselect.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.MultiselectWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) { // Parent constructor OO.ui.CheckboxMultiselectWidget.parent.call( this, config ); // Properties this.$lastClicked = null; // Events this.$group.on( 'click', this.onClick.bind( this ) ); // Initialization this.$element .addClass( 'oo-ui-checkboxMultiselectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget ); /* Methods */ /** * Get an option by its position relative to the specified item (or to the start of the option array, * if item is `null`). The direction in which to search through the option array is specified with a * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or * `null` if there are no options in the array. * * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array. * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select */ OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) { var currentIndex, nextIndex, i, increase = direction > 0 ? 1 : -1, len = this.items.length; if ( item ) { currentIndex = this.items.indexOf( item ); nextIndex = ( currentIndex + increase + len ) % len; } else { // If no item is selected and moving forward, start at the beginning. // If moving backward, start at the end. nextIndex = direction > 0 ? 0 : len - 1; } for ( i = 0; i < len; i++ ) { item = this.items[ nextIndex ]; if ( item && !item.isDisabled() ) { return item; } nextIndex = ( nextIndex + increase + len ) % len; } return null; }; /** * Handle click events on checkboxes. * * @param {jQuery.Event} e */ OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) { var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items, $lastClicked = this.$lastClicked, $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' ) .not( '.oo-ui-widget-disabled' ); // Allow selecting multiple options at once by Shift-clicking them if ( $lastClicked && $nowClicked.length && e.shiftKey ) { $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' ); lastClickedIndex = $options.index( $lastClicked ); nowClickedIndex = $options.index( $nowClicked ); // If it's the same item, either the user is being silly, or it's a fake event generated by the // browser. In either case we don't need custom handling. if ( nowClickedIndex !== lastClickedIndex ) { items = this.items; wasSelected = items[ nowClickedIndex ].isSelected(); direction = nowClickedIndex > lastClickedIndex ? 1 : -1; // This depends on the DOM order of the items and the order of the .items array being the same. for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) { if ( !items[ i ].isDisabled() ) { items[ i ].setSelected( !wasSelected ); } } // For the now-clicked element, use immediate timeout to allow the browser to do its own // handling first, then set our value. The order in which events happen is different for // clicks on the <input> and on the <label> and there are additional fake clicks fired for // non-click actions that change the checkboxes. e.preventDefault(); setTimeout( function () { if ( !items[ nowClickedIndex ].isDisabled() ) { items[ nowClickedIndex ].setSelected( !wasSelected ); } } ); } } if ( $nowClicked.length ) { this.$lastClicked = $nowClicked; } }; /** * FloatingMenuSelectWidget is a menu that will stick under a specified * container, even when it is inserted elsewhere in the document (for example, * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the * menu from being clipped too aggresively. * * The menu's position is automatically calculated and maintained when the menu * is toggled or the window is resized. * * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class. * * @class * @extends OO.ui.MenuSelectWidget * @mixins OO.ui.mixin.FloatableElement * * @constructor * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for. * Deprecated, omit this parameter and specify `$container` instead. * @param {Object} [config] Configuration options * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under */ OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) { // Allow 'inputWidget' parameter and config for backwards compatibility if ( OO.isPlainObject( inputWidget ) && config === undefined ) { config = inputWidget; inputWidget = config.inputWidget; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.FloatingMenuSelectWidget.parent.call( this, config ); // Properties (must be set before mixin constructors) this.inputWidget = inputWidget; // For backwards compatibility this.$container = config.$container || this.inputWidget.$element; // Mixins constructors OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) ); // Initialization this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' ); // For backwards compatibility this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget ); OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement ); /* Methods */ /** * @inheritdoc */ OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) { var change; visible = visible === undefined ? !this.isVisible() : !!visible; change = visible !== this.isVisible(); if ( change && visible ) { // Make sure the width is set before the parent method runs. this.setIdealSize( this.$container.width() ); } // Parent method // This will call this.clip(), which is nonsensical since we're not positioned yet... OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible ); if ( change ) { this.togglePositioning( this.isVisible() ); } return this; }; /* * The old name for the FloatingMenuSelectWidget widget, provided for backwards-compatibility. * * @class * @extends OO.ui.FloatingMenuSelectWidget * * @constructor * @deprecated since v0.12.5. */ OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget() { OO.ui.warnDeprecation( 'TextInputMenuSelectWidget is deprecated. Use the FloatingMenuSelectWidget instead.' ); // Parent constructor OO.ui.TextInputMenuSelectWidget.parent.apply( this, arguments ); }; OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.FloatingMenuSelectWidget ); /** * Progress bars visually display the status of an operation, such as a download, * and can be either determinate or indeterminate: * * - **determinate** process bars show the percent of an operation that is complete. * * - **indeterminate** process bars use a visual display of motion to indicate that an operation * is taking place. Because the extent of an indeterminate operation is unknown, the bar does * not use percentages. * * The value of the `progress` configuration determines whether the bar is determinate or indeterminate. * * @example * // Examples of determinate and indeterminate progress bars. * var progressBar1 = new OO.ui.ProgressBarWidget( { * progress: 33 * } ); * var progressBar2 = new OO.ui.ProgressBarWidget(); * * // Create a FieldsetLayout to layout progress bars * var fieldset = new OO.ui.FieldsetLayout; * fieldset.addItems( [ * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}), * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'}) * ] ); * $( 'body' ).append( fieldset.$element ); * * @class * @extends OO.ui.Widget * * @constructor * @param {Object} [config] Configuration options * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate). * To create a determinate progress bar, specify a number that reflects the initial percent complete. * By default, the progress bar is indeterminate. */ OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ProgressBarWidget.parent.call( this, config ); // Properties this.$bar = $( '<div>' ); this.progress = null; // Initialization this.setProgress( config.progress !== undefined ? config.progress : false ); this.$bar.addClass( 'oo-ui-progressBarWidget-bar' ); this.$element .attr( { role: 'progressbar', 'aria-valuemin': 0, 'aria-valuemax': 100 } ) .addClass( 'oo-ui-progressBarWidget' ) .append( this.$bar ); }; /* Setup */ OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.ProgressBarWidget.static.tagName = 'div'; /* Methods */ /** * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`. * * @return {number|boolean} Progress percent */ OO.ui.ProgressBarWidget.prototype.getProgress = function () { return this.progress; }; /** * Set the percent of the process completed or `false` for an indeterminate process. * * @param {number|boolean} progress Progress percent or `false` for indeterminate */ OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) { this.progress = progress; if ( progress !== false ) { this.$bar.css( 'width', this.progress + '%' ); this.$element.attr( 'aria-valuenow', this.progress ); } else { this.$bar.css( 'width', '' ); this.$element.removeAttr( 'aria-valuenow' ); } this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false ); }; /** * InputWidget is the base class for all input widgets, which * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs}, * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}. * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.TabIndexedElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.AccessKeyedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [name=''] The value of the input’s HTML `name` attribute. * @cfg {string} [value=''] The value of the input. * @cfg {string} [dir] The directionality of the input (ltr/rtl). * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input * before it is accepted. */ OO.ui.InputWidget = function OoUiInputWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.InputWidget.parent.call( this, config ); // Properties // See #reusePreInfuseDOM about config.$input this.$input = config.$input || this.getInputElement( config ); this.value = ''; this.inputFilter = config.inputFilter; // Mixin constructors OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) ); OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) ); // Events this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) ); // Initialization this.$input .addClass( 'oo-ui-inputWidget-input' ) .attr( 'name', config.name ) .prop( 'disabled', this.isDisabled() ); this.$element .addClass( 'oo-ui-inputWidget' ) .append( this.$input ); this.setValue( config.value ); if ( config.dir ) { this.setDir( config.dir ); } }; /* Setup */ OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement ); OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.InputWidget.static.supportsSimpleLabel = true; /* Static Methods */ /** * @inheritdoc */ OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) { config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config ); // Reusing $input lets browsers preserve inputted values across page reloads (T114134) config.$input = $( node ).find( '.oo-ui-inputWidget-input' ); return config; }; /** * @inheritdoc */ OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config ); if ( config.$input && config.$input.length ) { state.value = config.$input.val(); // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward state.focus = config.$input.is( ':focus' ); } return state; }; /* Events */ /** * @event change * * A change event is emitted when the value of the input changes. * * @param {string} value */ /* Methods */ /** * Get input element. * * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in * different circumstances. The element must have a `value` property (like form elements). * * @protected * @param {Object} config Configuration options * @return {jQuery} Input element */ OO.ui.InputWidget.prototype.getInputElement = function () { return $( '<input>' ); }; /** * Get input element's ID. * * If the element already has an ID then that is returned, otherwise unique ID is * generated, set on the element, and returned. * * @return {string} The ID of the element */ OO.ui.InputWidget.prototype.getInputId = function () { var id = this.$input.attr( 'id' ); if ( id === undefined ) { id = OO.ui.generateElementId(); this.$input.attr( 'id', id ); } return id; }; /** * Handle potentially value-changing events. * * @private * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event */ OO.ui.InputWidget.prototype.onEdit = function () { var widget = this; if ( !this.isDisabled() ) { // Allow the stack to clear so the value will be updated setTimeout( function () { widget.setValue( widget.$input.val() ); } ); } }; /** * Get the value of the input. * * @return {string} Input value */ OO.ui.InputWidget.prototype.getValue = function () { // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify // it, and we won't know unless they're kind enough to trigger a 'change' event. var value = this.$input.val(); if ( this.value !== value ) { this.setValue( value ); } return this.value; }; /** * Set the directionality of the input. * * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto' * @chainable */ OO.ui.InputWidget.prototype.setDir = function ( dir ) { this.$input.prop( 'dir', dir ); return this; }; /** * Set the value of the input. * * @param {string} value New value * @fires change * @chainable */ OO.ui.InputWidget.prototype.setValue = function ( value ) { value = this.cleanUpValue( value ); // Update the DOM if it has changed. Note that with cleanUpValue, it // is possible for the DOM value to change without this.value changing. if ( this.$input.val() !== value ) { this.$input.val( value ); } if ( this.value !== value ) { this.value = value; this.emit( 'change', this.value ); } return this; }; /** * Clean up incoming value. * * Ensures value is a string, and converts undefined and null to empty string. * * @private * @param {string} value Original value * @return {string} Cleaned up value */ OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) { if ( value === undefined || value === null ) { return ''; } else if ( this.inputFilter ) { return this.inputFilter( String( value ) ); } else { return String( value ); } }; /** * Simulate the behavior of clicking on a label bound to this input. This method is only called by * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be * called directly. */ OO.ui.InputWidget.prototype.simulateLabelClick = function () { OO.ui.warnDeprecation( 'InputWidget: simulateLabelClick() is deprecated.' ); if ( !this.isDisabled() ) { if ( this.$input.is( ':checkbox, :radio' ) ) { this.$input.click(); } if ( this.$input.is( ':input' ) ) { this.$input[ 0 ].focus(); } } }; /** * @inheritdoc */ OO.ui.InputWidget.prototype.setDisabled = function ( state ) { OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state ); if ( this.$input ) { this.$input.prop( 'disabled', this.isDisabled() ); } return this; }; /** * Focus the input. * * @chainable */ OO.ui.InputWidget.prototype.focus = function () { this.$input[ 0 ].focus(); return this; }; /** * Blur the input. * * @chainable */ OO.ui.InputWidget.prototype.blur = function () { this.$input[ 0 ].blur(); return this; }; /** * @inheritdoc */ OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) { OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state ); if ( state.value !== undefined && state.value !== this.getValue() ) { this.setValue( state.value ); } if ( state.focus ) { this.focus(); } }; /** * ButtonInputWidget is used to submit HTML forms and is intended to be used within * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an * HTML `<button>` (the default) or an HTML `<input>` tags. See the * [OOjs UI documentation on MediaWiki] [1] for more information. * * @example * // A ButtonInputWidget rendered as an HTML button, the default. * var button = new OO.ui.ButtonInputWidget( { * label: 'Input button', * icon: 'check', * value: 'check' * } ); * $( 'body' ).append( button.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs * * @class * @extends OO.ui.InputWidget * @mixins OO.ui.mixin.ButtonElement * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'. * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default. * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators}, * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only * be set to `true` when there’s need to support IE 6 in a form with multiple buttons. */ OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) { // Configuration initialization config = $.extend( { type: 'button', useInputTag: false }, config ); // See InputWidget#reusePreInfuseDOM about config.$input if ( config.$input ) { config.$input.empty(); } // Properties (must be set before parent constructor, which calls #setValue) this.useInputTag = config.useInputTag; // Parent constructor OO.ui.ButtonInputWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) ); OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) ); // Initialization if ( !config.useInputTag ) { this.$input.append( this.$icon, this.$label, this.$indicator ); } this.$element.addClass( 'oo-ui-buttonInputWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement ); /* Static Properties */ /** * Disable generating `<label>` elements for buttons. One would very rarely need additional label * for a button, and it's already a big clickable target, and it causes unexpected rendering. * * @static * @inheritdoc */ OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) { var type; type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button'; return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' ); }; /** * Set label value. * * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag. * * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or * text, or `null` for no label * @chainable */ OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) { if ( typeof label === 'function' ) { label = OO.ui.resolveMsg( label ); } if ( this.useInputTag ) { // Discard non-plaintext labels if ( typeof label !== 'string' ) { label = ''; } this.$input.val( label ); } return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label ); }; /** * Set the value of the input. * * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as * they do not support {@link #value values}. * * @param {string} value New value * @chainable */ OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) { if ( !this.useInputTag ) { OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value ); } return this; }; /** * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value. * Note that these {@link OO.ui.InputWidget input widgets} are best laid out * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline} * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1]. * * This widget can be used inside an HTML form, such as a OO.ui.FormLayout. * * @example * // An example of selected, unselected, and disabled checkbox inputs * var checkbox1=new OO.ui.CheckboxInputWidget( { * value: 'a', * selected: true * } ); * var checkbox2=new OO.ui.CheckboxInputWidget( { * value: 'b' * } ); * var checkbox3=new OO.ui.CheckboxInputWidget( { * value:'c', * disabled: true * } ); * // Create a fieldset layout with fields for each checkbox. * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Checkboxes' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ), * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ), * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ), * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected. */ OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.CheckboxInputWidget.parent.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-checkboxInputWidget' ) // Required for pretty styling in MediaWiki theme .append( $( '<span>' ) ); this.setSelected( config.selected !== undefined ? config.selected : false ); }; /* Setup */ OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget ); /* Static Methods */ /** * @inheritdoc */ OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config ); state.checked = config.$input.prop( 'checked' ); return state; }; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.CheckboxInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'checkbox' ); }; /** * @inheritdoc */ OO.ui.CheckboxInputWidget.prototype.onEdit = function () { var widget = this; if ( !this.isDisabled() ) { // Allow the stack to clear so the value will be updated setTimeout( function () { widget.setSelected( widget.$input.prop( 'checked' ) ); } ); } }; /** * Set selection state of this checkbox. * * @param {boolean} state `true` for selected * @chainable */ OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) { state = !!state; if ( this.selected !== state ) { this.selected = state; this.$input.prop( 'checked', this.selected ); this.emit( 'change', this.selected ); } return this; }; /** * Check if this checkbox is selected. * * @return {boolean} Checkbox is selected */ OO.ui.CheckboxInputWidget.prototype.isSelected = function () { // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify // it, and we won't know unless they're kind enough to trigger a 'change' event. var selected = this.$input.prop( 'checked' ); if ( this.selected !== selected ) { this.setSelected( selected ); } return this.selected; }; /** * @inheritdoc */ OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) { OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state ); if ( state.checked !== undefined && state.checked !== this.isSelected() ) { this.setSelected( state.checked ); } }; /** * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for * more information about input widgets. * * A DropdownInputWidget always has a value (one of the options is always selected), unless there * are no options. If no `value` configuration option is provided, the first option is selected. * If you need a state representing no value (no option being selected), use a DropdownWidget. * * This and OO.ui.RadioSelectInputWidget support the same configuration options. * * @example * // Example: A DropdownInputWidget with three options * var dropdownInput = new OO.ui.DropdownInputWidget( { * options: [ * { data: 'a', label: 'First' }, * { data: 'b', label: 'Second'}, * { data: 'c', label: 'Third' } * ] * } ); * $( 'body' ).append( dropdownInput.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {Object} [config] Configuration options * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }` * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget} */ OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) { // Configuration initialization config = config || {}; // See InputWidget#reusePreInfuseDOM about config.$input if ( config.$input ) { config.$input.addClass( 'oo-ui-element-hidden' ); } // Properties (must be done before parent constructor which calls #setDisabled) this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown ); // Parent constructor OO.ui.DropdownInputWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.TitledElement.call( this, config ); // Events this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } ); // Initialization this.setOptions( config.options || [] ); this.$element .addClass( 'oo-ui-dropdownInputWidget' ) .append( this.dropdownWidget.$element ); }; /* Setup */ OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget ); OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement ); /* Methods */ /** * @inheritdoc * @protected */ OO.ui.DropdownInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'hidden' ); }; /** * Handles menu select events. * * @private * @param {OO.ui.MenuOptionWidget} item Selected menu item */ OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) { this.setValue( item.getData() ); }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) { value = this.cleanUpValue( value ); this.dropdownWidget.getMenu().selectItemByData( value ); OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value ); return this; }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) { this.dropdownWidget.setDisabled( state ); OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state ); return this; }; /** * Set the options available for this input. * * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }` * @chainable */ OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) { var value = this.getValue(), widget = this; // Rebuild the dropdown menu this.dropdownWidget.getMenu() .clearItems() .addItems( options.map( function ( opt ) { var optValue = widget.cleanUpValue( opt.data ); return new OO.ui.MenuOptionWidget( { data: optValue, label: opt.label !== undefined ? opt.label : optValue } ); } ) ); // Restore the previous value, or reset to something sensible if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) { // Previous value is still available, ensure consistency with the dropdown this.setValue( value ); } else { // No longer valid, reset if ( options.length ) { this.setValue( options[ 0 ].data ); } } return this; }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.focus = function () { this.dropdownWidget.getMenu().toggle( true ); return this; }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.blur = function () { this.dropdownWidget.getMenu().toggle( false ); return this; }; /** * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set, * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select} * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information, * please see the [OOjs UI documentation on MediaWiki][1]. * * This widget can be used inside an HTML form, such as a OO.ui.FormLayout. * * @example * // An example of selected, unselected, and disabled radio inputs * var radio1 = new OO.ui.RadioInputWidget( { * value: 'a', * selected: true * } ); * var radio2 = new OO.ui.RadioInputWidget( { * value: 'b' * } ); * var radio3 = new OO.ui.RadioInputWidget( { * value: 'c', * disabled: true * } ); * // Create a fieldset layout with fields for each radio button. * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Radio inputs' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ), * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ), * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ), * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected. */ OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.RadioInputWidget.parent.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-radioInputWidget' ) // Required for pretty styling in MediaWiki theme .append( $( '<span>' ) ); this.setSelected( config.selected !== undefined ? config.selected : false ); }; /* Setup */ OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget ); /* Static Methods */ /** * @inheritdoc */ OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config ); state.checked = config.$input.prop( 'checked' ); return state; }; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.RadioInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'radio' ); }; /** * @inheritdoc */ OO.ui.RadioInputWidget.prototype.onEdit = function () { // RadioInputWidget doesn't track its state. }; /** * Set selection state of this radio button. * * @param {boolean} state `true` for selected * @chainable */ OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) { // RadioInputWidget doesn't track its state. this.$input.prop( 'checked', state ); return this; }; /** * Check if this radio button is selected. * * @return {boolean} Radio is selected */ OO.ui.RadioInputWidget.prototype.isSelected = function () { return this.$input.prop( 'checked' ); }; /** * @inheritdoc */ OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) { OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state ); if ( state.checked !== undefined && state.checked !== this.isSelected() ) { this.setSelected( state.checked ); } }; /** * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for * more information about input widgets. * * This and OO.ui.DropdownInputWidget support the same configuration options. * * @example * // Example: A RadioSelectInputWidget with three options * var radioSelectInput = new OO.ui.RadioSelectInputWidget( { * options: [ * { data: 'a', label: 'First' }, * { data: 'b', label: 'Second'}, * { data: 'c', label: 'Third' } * ] * } ); * $( 'body' ).append( radioSelectInput.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }` */ OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.radioSelectWidget = new OO.ui.RadioSelectWidget(); // Parent constructor OO.ui.RadioSelectInputWidget.parent.call( this, config ); // Events this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } ); // Initialization this.setOptions( config.options || [] ); this.$element .addClass( 'oo-ui-radioSelectInputWidget' ) .append( this.radioSelectWidget.$element ); }; /* Setup */ OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false; /* Static Methods */ /** * @inheritdoc */ OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config ); state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val(); return state; }; /** * @inheritdoc */ OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) { config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config ); // Cannot reuse the `<input type=radio>` set delete config.$input; return config; }; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'hidden' ); }; /** * Handles menu select events. * * @private * @param {OO.ui.RadioOptionWidget} item Selected menu item */ OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) { this.setValue( item.getData() ); }; /** * @inheritdoc */ OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) { value = this.cleanUpValue( value ); this.radioSelectWidget.selectItemByData( value ); OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value ); return this; }; /** * @inheritdoc */ OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) { this.radioSelectWidget.setDisabled( state ); OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state ); return this; }; /** * Set the options available for this input. * * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }` * @chainable */ OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) { var value = this.getValue(), widget = this; // Rebuild the radioSelect menu this.radioSelectWidget .clearItems() .addItems( options.map( function ( opt ) { var optValue = widget.cleanUpValue( opt.data ); return new OO.ui.RadioOptionWidget( { data: optValue, label: opt.label !== undefined ? opt.label : optValue } ); } ) ); // Restore the previous value, or reset to something sensible if ( this.radioSelectWidget.getItemFromData( value ) ) { // Previous value is still available, ensure consistency with the radioSelect this.setValue( value ); } else { // No longer valid, reset if ( options.length ) { this.setValue( options[ 0 ].data ); } } return this; }; /** * CheckboxMultiselectInputWidget is a * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for * more information about input widgets. * * @example * // Example: A CheckboxMultiselectInputWidget with three options * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( { * options: [ * { data: 'a', label: 'First' }, * { data: 'b', label: 'Second'}, * { data: 'c', label: 'Third' } * ] * } ); * $( 'body' ).append( multiselectInput.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }` */ OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget(); // Parent constructor OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config ); // Properties this.inputName = config.name; // Initialization this.$element .addClass( 'oo-ui-checkboxMultiselectInputWidget' ) .append( this.checkboxMultiselectWidget.$element ); // We don't use this.$input, but rather the CheckboxInputWidgets inside each option this.$input.detach(); this.setOptions( config.options || [] ); // Have to repeat this from parent, as we need options to be set up for this to make sense this.setValue( config.value ); }; /* Setup */ OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.static.supportsSimpleLabel = false; /* Static Methods */ /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config ); state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' ) .toArray().map( function ( el ) { return el.value; } ); return state; }; /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) { config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config ); // Cannot reuse the `<input type=checkbox>` set delete config.$input; return config; }; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () { // Actually unused return $( '<div>' ); }; /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () { var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' ) .toArray().map( function ( el ) { return el.value; } ); if ( this.value !== value ) { this.setValue( value ); } return this.value; }; /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) { value = this.cleanUpValue( value ); this.checkboxMultiselectWidget.selectItemsByData( value ); OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value ); return this; }; /** * Clean up incoming value. * * @param {string[]} value Original value * @return {string[]} Cleaned up value */ OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) { var i, singleValue, cleanValue = []; if ( !Array.isArray( value ) ) { return cleanValue; } for ( i = 0; i < value.length; i++ ) { singleValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] ); // Remove options that we don't have here if ( !this.checkboxMultiselectWidget.getItemFromData( singleValue ) ) { continue; } cleanValue.push( singleValue ); } return cleanValue; }; /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) { this.checkboxMultiselectWidget.setDisabled( state ); OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state ); return this; }; /** * Set the options available for this input. * * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }` * @chainable */ OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) { var widget = this; // Rebuild the checkboxMultiselectWidget menu this.checkboxMultiselectWidget .clearItems() .addItems( options.map( function ( opt ) { var optValue, item, optDisabled; optValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data ); optDisabled = opt.disabled !== undefined ? opt.disabled : false; item = new OO.ui.CheckboxMultioptionWidget( { data: optValue, label: opt.label !== undefined ? opt.label : optValue, disabled: optDisabled } ); // Set the 'name' and 'value' for form submission item.checkbox.$input.attr( 'name', widget.inputName ); item.checkbox.setValue( optValue ); return item; } ) ); // Re-set the value, checking the checkboxes as needed. // This will also get rid of any stale options that we just removed. this.setValue( this.getValue() ); return this; }; /** * TextInputWidgets, like HTML text inputs, can be configured with options that customize the * size of the field as well as its presentation. In addition, these widgets can be configured * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional * validation-pattern (used to determine if an input value is valid or not) and an input filter, * which modifies incoming values rather than validating them. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples. * * This widget can be used inside an HTML form, such as a OO.ui.FormLayout. * * @example * // Example of a text input widget * var textInput = new OO.ui.TextInputWidget( { * value: 'Text input' * } ) * $( 'body' ).append( textInput.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.PendingElement * @mixins OO.ui.mixin.LabelElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search', * 'email', 'url', 'date', 'month' or 'number'. Ignored if `multiline` is true. * * Some values of `type` result in additional behaviors: * * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator * empties the text field * @cfg {string} [placeholder] Placeholder text * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to * instruct the browser to focus this widget. * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input. * @cfg {number} [maxLength] Maximum number of characters allowed in the input. * @cfg {boolean} [multiline=false] Allow multiple lines of text * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`, * specifies minimum number of rows to display. * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content. * Use the #maxRows config to specify a maximum number of displayed rows. * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true. * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided. * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of * the value or placeholder text: `'before'` or `'after'` * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`. * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' * (the value must contain only numbers); when RegExp, a regular expression that must match the * value for it to be considered valid; when Function, a function receiving the value as parameter * that must return true, or promise resolving to true, for it to be considered valid. */ OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) { // Configuration initialization config = $.extend( { type: 'text', labelPosition: 'after' }, config ); if ( config.type === 'search' ) { OO.ui.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' ); if ( config.icon === undefined ) { config.icon = 'search'; } // indicator: 'clear' is set dynamically later, depending on value } // Parent constructor OO.ui.TextInputWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) ); OO.ui.mixin.LabelElement.call( this, config ); // Properties this.type = this.getSaneType( config ); this.readOnly = false; this.required = false; this.multiline = !!config.multiline; this.autosize = !!config.autosize; this.minRows = config.rows !== undefined ? config.rows : ''; this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 ); this.validate = null; this.styleHeight = null; this.scrollWidth = null; // Clone for resizing if ( this.autosize ) { this.$clone = this.$input .clone() .insertAfter( this.$input ) .attr( 'aria-hidden', 'true' ) .addClass( 'oo-ui-element-hidden' ); } this.setValidation( config.validate ); this.setLabelPosition( config.labelPosition ); // Events this.$input.on( { keypress: this.onKeyPress.bind( this ), blur: this.onBlur.bind( this ), focus: this.onFocus.bind( this ) } ); this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) ); this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) ); this.on( 'labelChange', this.updatePosition.bind( this ) ); this.connect( this, { change: 'onChange', disable: 'onDisable' } ); this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) ); // Initialization this.$element .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type ) .append( this.$icon, this.$indicator ); this.setReadOnly( !!config.readOnly ); this.setRequired( !!config.required ); this.updateSearchIndicator(); if ( config.placeholder !== undefined ) { this.$input.attr( 'placeholder', config.placeholder ); } if ( config.maxLength !== undefined ) { this.$input.attr( 'maxlength', config.maxLength ); } if ( config.autofocus ) { this.$input.attr( 'autofocus', 'autofocus' ); } if ( config.autocomplete === false ) { this.$input.attr( 'autocomplete', 'off' ); // Turning off autocompletion also disables "form caching" when the user navigates to a // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI. $( window ).on( { beforeunload: function () { this.$input.removeAttr( 'autocomplete' ); }.bind( this ), pageshow: function () { // Browsers don't seem to actually fire this event on "Back", they instead just reload the // whole page... it shouldn't hurt, though. this.$input.attr( 'autocomplete', 'off' ); }.bind( this ) } ); } if ( this.multiline && config.rows ) { this.$input.attr( 'rows', config.rows ); } if ( this.label || config.autosize ) { this.isWaitingToBeAttached = true; this.installParentChangeDetector(); } }; /* Setup */ OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement ); /* Static Properties */ OO.ui.TextInputWidget.static.validationPatterns = { 'non-empty': /.+/, integer: /^\d+$/ }; /* Static Methods */ /** * @inheritdoc */ OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config ); if ( config.multiline ) { state.scrollTop = config.$input.scrollTop(); } return state; }; /* Events */ /** * An `enter` event is emitted when the user presses 'enter' inside the text box. * * Not emitted if the input is multiline. * * @event enter */ /** * A `resize` event is emitted when autosize is set and the widget resizes * * @event resize */ /* Methods */ /** * Handle icon mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) { if ( e.which === OO.ui.MouseButtons.LEFT ) { this.$input[ 0 ].focus(); return false; } }; /** * Handle indicator mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) { if ( e.which === OO.ui.MouseButtons.LEFT ) { if ( this.type === 'search' ) { // Clear the text field this.setValue( '' ); } this.$input[ 0 ].focus(); return false; } }; /** * Handle key press events. * * @private * @param {jQuery.Event} e Key press event * @fires enter If enter key is pressed and input is not multiline */ OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) { if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) { this.emit( 'enter', e ); } }; /** * Handle blur events. * * @private * @param {jQuery.Event} e Blur event */ OO.ui.TextInputWidget.prototype.onBlur = function () { this.setValidityFlag(); }; /** * Handle focus events. * * @private * @param {jQuery.Event} e Focus event */ OO.ui.TextInputWidget.prototype.onFocus = function () { if ( this.isWaitingToBeAttached ) { // If we've received focus, then we must be attached to the document, and if // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now. this.onElementAttach(); } this.setValidityFlag( true ); }; /** * Handle element attach events. * * @private * @param {jQuery.Event} e Element attach event */ OO.ui.TextInputWidget.prototype.onElementAttach = function () { this.isWaitingToBeAttached = false; // Any previously calculated size is now probably invalid if we reattached elsewhere this.valCache = null; this.adjustSize(); this.positionLabel(); }; /** * Handle change events. * * @param {string} value * @private */ OO.ui.TextInputWidget.prototype.onChange = function () { this.updateSearchIndicator(); this.adjustSize(); }; /** * Handle debounced change events. * * @param {string} value * @private */ OO.ui.TextInputWidget.prototype.onDebouncedChange = function () { this.setValidityFlag(); }; /** * Handle disable events. * * @param {boolean} disabled Element is disabled * @private */ OO.ui.TextInputWidget.prototype.onDisable = function () { this.updateSearchIndicator(); }; /** * Check if the input is {@link #readOnly read-only}. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isReadOnly = function () { return this.readOnly; }; /** * Set the {@link #readOnly read-only} state of the input. * * @param {boolean} state Make input read-only * @chainable */ OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) { this.readOnly = !!state; this.$input.prop( 'readOnly', this.readOnly ); this.updateSearchIndicator(); return this; }; /** * Check if the input is {@link #required required}. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isRequired = function () { return this.required; }; /** * Set the {@link #required required} state of the input. * * @param {boolean} state Make input required * @chainable */ OO.ui.TextInputWidget.prototype.setRequired = function ( state ) { this.required = !!state; if ( this.required ) { this.$input .attr( 'required', 'required' ) .attr( 'aria-required', 'true' ); if ( this.getIndicator() === null ) { this.setIndicator( 'required' ); } } else { this.$input .removeAttr( 'required' ) .removeAttr( 'aria-required' ); if ( this.getIndicator() === 'required' ) { this.setIndicator( null ); } } this.updateSearchIndicator(); return this; }; /** * Support function for making #onElementAttach work across browsers. * * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback. * * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the * first time that the element gets attached to the documented. */ OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () { var mutationObserver, onRemove, topmostNode, fakeParentNode, MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver, widget = this; if ( MutationObserver ) { // The new way. If only it wasn't so ugly. if ( this.isElementAttached() ) { // Widget is attached already, do nothing. This breaks the functionality of this function when // the widget is detached and reattached. Alas, doing this correctly with MutationObserver // would require observation of the whole document, which would hurt performance of other, // more important code. return; } // Find topmost node in the tree topmostNode = this.$element[ 0 ]; while ( topmostNode.parentNode ) { topmostNode = topmostNode.parentNode; } // We have no way to detect the $element being attached somewhere without observing the entire // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the // parent node of $element, and instead detect when $element is removed from it (and thus // probably attached somewhere else). If there is no parent, we create a "fake" one. If it // doesn't get attached, we end up back here and create the parent. mutationObserver = new MutationObserver( function ( mutations ) { var i, j, removedNodes; for ( i = 0; i < mutations.length; i++ ) { removedNodes = mutations[ i ].removedNodes; for ( j = 0; j < removedNodes.length; j++ ) { if ( removedNodes[ j ] === topmostNode ) { setTimeout( onRemove, 0 ); return; } } } } ); onRemove = function () { // If the node was attached somewhere else, report it if ( widget.isElementAttached() ) { widget.onElementAttach(); } mutationObserver.disconnect(); widget.installParentChangeDetector(); }; // Create a fake parent and observe it fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ]; mutationObserver.observe( fakeParentNode, { childList: true } ); } else { // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated. this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) ); } }; /** * Automatically adjust the size of the text input. * * This only affects #multiline inputs that are {@link #autosize autosized}. * * @chainable * @fires resize */ OO.ui.TextInputWidget.prototype.adjustSize = function () { var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight, newHeight, scrollWidth, property; if ( this.isWaitingToBeAttached ) { // #onElementAttach will be called soon, which calls this method return this; } if ( this.multiline && this.$input.val() !== this.valCache ) { if ( this.autosize ) { this.$clone .val( this.$input.val() ) .attr( 'rows', this.minRows ) // Set inline height property to 0 to measure scroll height .css( 'height', 0 ); this.$clone.removeClass( 'oo-ui-element-hidden' ); this.valCache = this.$input.val(); scrollHeight = this.$clone[ 0 ].scrollHeight; // Remove inline height property to measure natural heights this.$clone.css( 'height', '' ); innerHeight = this.$clone.innerHeight(); outerHeight = this.$clone.outerHeight(); // Measure max rows height this.$clone .attr( 'rows', this.maxRows ) .css( 'height', 'auto' ) .val( '' ); maxInnerHeight = this.$clone.innerHeight(); // Difference between reported innerHeight and scrollHeight with no scrollbars present. // This is sometimes non-zero on Blink-based browsers, depending on zoom level. measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight; idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError ); this.$clone.addClass( 'oo-ui-element-hidden' ); // Only apply inline height when expansion beyond natural height is needed // Use the difference between the inner and outer height as a buffer newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : ''; if ( newHeight !== this.styleHeight ) { this.$input.css( 'height', newHeight ); this.styleHeight = newHeight; this.emit( 'resize' ); } } scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth; if ( scrollWidth !== this.scrollWidth ) { property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right'; // Reset this.$label.css( { right: '', left: '' } ); this.$indicator.css( { right: '', left: '' } ); if ( scrollWidth ) { this.$indicator.css( property, scrollWidth ); if ( this.labelPosition === 'after' ) { this.$label.css( property, scrollWidth ); } } this.scrollWidth = scrollWidth; this.positionLabel(); } } return this; }; /** * @inheritdoc * @protected */ OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) { if ( config.multiline ) { return $( '<textarea>' ); } else if ( this.getSaneType( config ) === 'number' ) { return $( '<input>' ) .attr( 'step', 'any' ) .attr( 'type', 'number' ); } else { return $( '<input>' ).attr( 'type', this.getSaneType( config ) ); } }; /** * Get sanitized value for 'type' for given config. * * @param {Object} config Configuration options * @return {string|null} * @private */ OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) { var allowedTypes = [ 'text', 'password', 'search', 'email', 'url', 'date', 'month', 'number' ]; return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text'; }; /** * Check if the input supports multiple lines. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isMultiline = function () { return !!this.multiline; }; /** * Check if the input automatically adjusts its size. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isAutosizing = function () { return !!this.autosize; }; /** * Focus the input and select a specified range within the text. * * @param {number} from Select from offset * @param {number} [to] Select to offset, defaults to from * @chainable */ OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) { var isBackwards, start, end, input = this.$input[ 0 ]; to = to || from; isBackwards = to < from; start = isBackwards ? to : from; end = isBackwards ? from : to; this.focus(); try { input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' ); } catch ( e ) { // IE throws an exception if you call setSelectionRange on a unattached DOM node. // Rather than expensively check if the input is attached every time, just check // if it was the cause of an error being thrown. If not, rethrow the error. if ( this.getElementDocument().body.contains( input ) ) { throw e; } } return this; }; /** * Get an object describing the current selection range in a directional manner * * @return {Object} Object containing 'from' and 'to' offsets */ OO.ui.TextInputWidget.prototype.getRange = function () { var input = this.$input[ 0 ], start = input.selectionStart, end = input.selectionEnd, isBackwards = input.selectionDirection === 'backward'; return { from: isBackwards ? end : start, to: isBackwards ? start : end }; }; /** * Get the length of the text input value. * * This could differ from the length of #getValue if the * value gets filtered * * @return {number} Input length */ OO.ui.TextInputWidget.prototype.getInputLength = function () { return this.$input[ 0 ].value.length; }; /** * Focus the input and select the entire text. * * @chainable */ OO.ui.TextInputWidget.prototype.select = function () { return this.selectRange( 0, this.getInputLength() ); }; /** * Focus the input and move the cursor to the start. * * @chainable */ OO.ui.TextInputWidget.prototype.moveCursorToStart = function () { return this.selectRange( 0 ); }; /** * Focus the input and move the cursor to the end. * * @chainable */ OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () { return this.selectRange( this.getInputLength() ); }; /** * Insert new content into the input. * * @param {string} content Content to be inserted * @chainable */ OO.ui.TextInputWidget.prototype.insertContent = function ( content ) { var start, end, range = this.getRange(), value = this.getValue(); start = Math.min( range.from, range.to ); end = Math.max( range.from, range.to ); this.setValue( value.slice( 0, start ) + content + value.slice( end ) ); this.selectRange( start + content.length ); return this; }; /** * Insert new content either side of a selection. * * @param {string} pre Content to be inserted before the selection * @param {string} post Content to be inserted after the selection * @chainable */ OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) { var start, end, range = this.getRange(), offset = pre.length; start = Math.min( range.from, range.to ); end = Math.max( range.from, range.to ); this.selectRange( start ).insertContent( pre ); this.selectRange( offset + end ).insertContent( post ); this.selectRange( offset + start, offset + end ); return this; }; /** * Set the validation pattern. * * The validation pattern is either a regular expression, a function, or the symbolic name of a * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the * value must contain only numbers). * * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class. */ OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) { if ( validate instanceof RegExp || validate instanceof Function ) { this.validate = validate; } else { this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/; } }; /** * Sets the 'invalid' flag appropriately. * * @param {boolean} [isValid] Optionally override validation result */ OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) { var widget = this, setFlag = function ( valid ) { if ( !valid ) { widget.$input.attr( 'aria-invalid', 'true' ); } else { widget.$input.removeAttr( 'aria-invalid' ); } widget.setFlags( { invalid: !valid } ); }; if ( isValid !== undefined ) { setFlag( isValid ); } else { this.getValidity().then( function () { setFlag( true ); }, function () { setFlag( false ); } ); } }; /** * Get the validity of current value. * * This method returns a promise that resolves if the value is valid and rejects if * it isn't. Uses the {@link #validate validation pattern} to check for validity. * * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not. */ OO.ui.TextInputWidget.prototype.getValidity = function () { var result; function rejectOrResolve( valid ) { if ( valid ) { return $.Deferred().resolve().promise(); } else { return $.Deferred().reject().promise(); } } // Check browser validity and reject if it is invalid if ( this.$input[ 0 ].checkValidity !== undefined && this.$input[ 0 ].checkValidity() === false ) { return rejectOrResolve( false ); } // Run our checks if the browser thinks the field is valid if ( this.validate instanceof Function ) { result = this.validate( this.getValue() ); if ( result && $.isFunction( result.promise ) ) { return result.promise().then( function ( valid ) { return rejectOrResolve( valid ); } ); } else { return rejectOrResolve( result ); } } else { return rejectOrResolve( this.getValue().match( this.validate ) ); } }; /** * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`. * * @param {string} labelPosition Label position, 'before' or 'after' * @chainable */ OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) { this.labelPosition = labelPosition; if ( this.label ) { // If there is no label and we only change the position, #updatePosition is a no-op, // but it takes really a lot of work to do nothing. this.updatePosition(); } return this; }; /** * Update the position of the inline label. * * This method is called by #setLabelPosition, and can also be called on its own if * something causes the label to be mispositioned. * * @chainable */ OO.ui.TextInputWidget.prototype.updatePosition = function () { var after = this.labelPosition === 'after'; this.$element .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after ) .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after ); this.valCache = null; this.scrollWidth = null; this.adjustSize(); this.positionLabel(); return this; }; /** * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is * already empty or when it's not editable. */ OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () { if ( this.type === 'search' ) { if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) { this.setIndicator( null ); } else { this.setIndicator( 'clear' ); } } }; /** * Position the label by setting the correct padding on the input. * * @private * @chainable */ OO.ui.TextInputWidget.prototype.positionLabel = function () { var after, rtl, property; if ( this.isWaitingToBeAttached ) { // #onElementAttach will be called soon, which calls this method return this; } // Clear old values this.$input // Clear old values if present .css( { 'padding-right': '', 'padding-left': '' } ); if ( this.label ) { this.$element.append( this.$label ); } else { this.$label.detach(); return; } after = this.labelPosition === 'after'; rtl = this.$element.css( 'direction' ) === 'rtl'; property = after === rtl ? 'padding-left' : 'padding-right'; this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) ); return this; }; /** * @inheritdoc */ OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) { OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state ); if ( state.scrollTop !== undefined ) { this.$input.scrollTop( state.scrollTop ); } }; /** * @class * @extends OO.ui.TextInputWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) { config = $.extend( { icon: 'search' }, config ); // Set type to text so that TextInputWidget doesn't // get stuck in an infinite loop. config.type = 'text'; // Parent constructor OO.ui.SearchInputWidget.parent.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-textInputWidget-type-search' ); this.updateSearchIndicator(); this.connect( this, { disable: 'onDisable' } ); }; /* Setup */ OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget ); /* Methods */ /** * @inheritdoc * @protected */ OO.ui.SearchInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'search' ); }; /** * @inheritdoc */ OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) { if ( e.which === OO.ui.MouseButtons.LEFT ) { // Clear the text field this.setValue( '' ); this.$input[ 0 ].focus(); return false; } }; /** * Update the 'clear' indicator displayed on type: 'search' text * fields, hiding it when the field is already empty or when it's not * editable. */ OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () { if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) { this.setIndicator( null ); } else { this.setIndicator( 'clear' ); } }; /** * @inheritdoc */ OO.ui.SearchInputWidget.prototype.onChange = function () { OO.ui.SearchInputWidget.parent.prototype.onChange.call( this ); this.updateSearchIndicator(); }; /** * Handle disable events. * * @param {boolean} disabled Element is disabled * @private */ OO.ui.SearchInputWidget.prototype.onDisable = function () { this.updateSearchIndicator(); }; /** * @inheritdoc */ OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) { OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state ); this.updateSearchIndicator(); return this; }; /** * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which * a value can be chosen instead). Users can choose options from the combo box in one of two ways: * * - by typing a value in the text input field. If the value exactly matches the value of a menu * option, that option will appear to be selected. * - by choosing a value from the menu. The value of the chosen option will then appear in the text * input field. * * This widget can be used inside an HTML form, such as a OO.ui.FormLayout. * * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example: A ComboBoxInputWidget. * var comboBox = new OO.ui.ComboBoxInputWidget( { * label: 'ComboBoxInputWidget', * value: 'Option 1', * menu: { * items: [ * new OO.ui.MenuOptionWidget( { * data: 'Option 1', * label: 'Option One' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 2', * label: 'Option Two' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 3', * label: 'Option Three' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 4', * label: 'Option Four' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 5', * label: 'Option Five' * } ) * ] * } * } ); * $( 'body' ).append( comboBox.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.TextInputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }` * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}. * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the * containing `<div>` and has a larger area. By default, the menu uses relative positioning. */ OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) { // Configuration initialization config = $.extend( { autocomplete: false }, config ); // ComboBoxInputWidget shouldn't support multiline config.multiline = false; // Parent constructor OO.ui.ComboBoxInputWidget.parent.call( this, config ); // Properties this.$overlay = config.$overlay || this.$element; this.dropdownButton = new OO.ui.ButtonWidget( { classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ], indicator: 'down', disabled: this.disabled } ); this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( { widget: this, input: this, $container: this.$element, disabled: this.isDisabled() }, config.menu ) ); // Events this.connect( this, { change: 'onInputChange', enter: 'onInputEnter' } ); this.dropdownButton.connect( this, { click: 'onDropdownButtonClick' } ); this.menu.connect( this, { choose: 'onMenuChoose', add: 'onMenuItemsChange', remove: 'onMenuItemsChange' } ); // Initialization this.$input.attr( { role: 'combobox', 'aria-autocomplete': 'list' } ); // Do not override options set via config.menu.items if ( config.options !== undefined ) { this.setOptions( config.options ); } this.$field = $( '<div>' ) .addClass( 'oo-ui-comboBoxInputWidget-field' ) .append( this.$input, this.dropdownButton.$element ); this.$element .addClass( 'oo-ui-comboBoxInputWidget' ) .append( this.$field ); this.$overlay.append( this.menu.$element ); this.onMenuItemsChange(); }; /* Setup */ OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget ); /* Methods */ /** * Get the combobox's menu. * * @return {OO.ui.FloatingMenuSelectWidget} Menu widget */ OO.ui.ComboBoxInputWidget.prototype.getMenu = function () { return this.menu; }; /** * Get the combobox's text input widget. * * @return {OO.ui.TextInputWidget} Text input widget */ OO.ui.ComboBoxInputWidget.prototype.getInput = function () { return this; }; /** * Handle input change events. * * @private * @param {string} value New value */ OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) { var match = this.menu.getItemFromData( value ); this.menu.selectItem( match ); if ( this.menu.getHighlightedItem() ) { this.menu.highlightItem( match ); } if ( !this.isDisabled() ) { this.menu.toggle( true ); } }; /** * Handle input enter events. * * @private */ OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () { if ( !this.isDisabled() ) { this.menu.toggle( false ); } }; /** * Handle button click events. * * @private */ OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () { this.menu.toggle(); this.$input[ 0 ].focus(); }; /** * Handle menu choose events. * * @private * @param {OO.ui.OptionWidget} item Chosen item */ OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) { this.setValue( item.getData() ); }; /** * Handle menu item change events. * * @private */ OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () { var match = this.menu.getItemFromData( this.getValue() ); this.menu.selectItem( match ); if ( this.menu.getHighlightedItem() ) { this.menu.highlightItem( match ); } this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() ); }; /** * @inheritdoc */ OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) { // Parent method OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled ); if ( this.dropdownButton ) { this.dropdownButton.setDisabled( this.isDisabled() ); } if ( this.menu ) { this.menu.setDisabled( this.isDisabled() ); } return this; }; /** * Set the options available for this input. * * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }` * @chainable */ OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) { this.getMenu() .clearItems() .addItems( options.map( function ( opt ) { return new OO.ui.MenuOptionWidget( { data: opt.data, label: opt.label !== undefined ? opt.label : opt.data } ); } ) ); return this; }; /** * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget, * which is a widget that is specified by reference before any optional configuration settings. * * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways: * * - **left**: The label is placed before the field-widget and aligned with the left margin. * A left-alignment is used for forms with many fields. * - **right**: The label is placed before the field-widget and aligned to the right margin. * A right-alignment is used for long but familiar forms which users tab through, * verifying the current field with a quick glance at the label. * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms * that users fill out from top to bottom. * - **inline**: The label is placed after the field-widget and aligned to the left. * An inline-alignment is best used with checkboxes or radio buttons. * * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout. * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets * * @class * @extends OO.ui.Layout * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {OO.ui.Widget} fieldWidget Field widget * @param {Object} [config] Configuration options * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline' * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget. * The array may contain strings or OO.ui.HtmlSnippet instances. * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget. * The array may contain strings or OO.ui.HtmlSnippet instances. * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear * in the upper-right corner of the rendered field; clicking it will display the text in a popup. * For important messages, you are advised to use `notices`, as they are always shown. * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given. * * @throws {Error} An error is thrown if no widget is specified */ OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( fieldWidget ) && config === undefined ) { config = fieldWidget; fieldWidget = config.fieldWidget; } // Make sure we have required constructor arguments if ( fieldWidget === undefined ) { throw new Error( 'Widget not found' ); } // Configuration initialization config = $.extend( { align: 'left' }, config ); // Parent constructor OO.ui.FieldLayout.parent.call( this, config ); // Mixin constructors OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: $( '<label>' ) } ) ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) ); // Properties this.fieldWidget = fieldWidget; this.errors = []; this.notices = []; this.$field = $( '<div>' ); this.$messages = $( '<ul>' ); this.$header = $( '<div>' ); this.$body = $( '<div>' ); this.align = null; if ( config.help ) { this.popupButtonWidget = new OO.ui.PopupButtonWidget( { $overlay: config.$overlay, popup: { padded: true }, classes: [ 'oo-ui-fieldLayout-help' ], framed: false, icon: 'info' } ); if ( config.help instanceof OO.ui.HtmlSnippet ) { this.popupButtonWidget.getPopup().$body.html( config.help.toString() ); } else { this.popupButtonWidget.getPopup().$body.text( config.help ); } this.$help = this.popupButtonWidget.$element; } else { this.$help = $( [] ); } // Events this.fieldWidget.connect( this, { disable: 'onFieldDisable' } ); // Initialization if ( fieldWidget.constructor.static.supportsSimpleLabel ) { if ( this.fieldWidget.getInputId() ) { this.$label.attr( 'for', this.fieldWidget.getInputId() ); } else { this.$label.on( 'click', function () { this.fieldWidget.focus(); return false; }.bind( this ) ); } } this.$element .addClass( 'oo-ui-fieldLayout' ) .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() ) .append( this.$body ); this.$body.addClass( 'oo-ui-fieldLayout-body' ); this.$header.addClass( 'oo-ui-fieldLayout-header' ); this.$messages.addClass( 'oo-ui-fieldLayout-messages' ); this.$field .addClass( 'oo-ui-fieldLayout-field' ) .append( this.fieldWidget.$element ); this.setErrors( config.errors || [] ); this.setNotices( config.notices || [] ); this.setAlignment( config.align ); }; /* Setup */ OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement ); /* Methods */ /** * Handle field disable events. * * @private * @param {boolean} value Field is disabled */ OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) { this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value ); }; /** * Get the widget contained by the field. * * @return {OO.ui.Widget} Field widget */ OO.ui.FieldLayout.prototype.getField = function () { return this.fieldWidget; }; /** * @protected * @param {string} kind 'error' or 'notice' * @param {string|OO.ui.HtmlSnippet} text * @return {jQuery} */ OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) { var $listItem, $icon, message; $listItem = $( '<li>' ); if ( kind === 'error' ) { $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element; } else if ( kind === 'notice' ) { $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element; } else { $icon = ''; } message = new OO.ui.LabelWidget( { label: text } ); $listItem .append( $icon, message.$element ) .addClass( 'oo-ui-fieldLayout-messages-' + kind ); return $listItem; }; /** * Set the field alignment mode. * * @private * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline' * @chainable */ OO.ui.FieldLayout.prototype.setAlignment = function ( value ) { if ( value !== this.align ) { // Default to 'left' if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) { value = 'left'; } // Reorder elements if ( value === 'top' ) { this.$header.append( this.$label, this.$help ); this.$body.append( this.$header, this.$field ); } else if ( value === 'inline' ) { this.$header.append( this.$label, this.$help ); this.$body.append( this.$field, this.$header ); } else { this.$header.append( this.$label ); this.$body.append( this.$header, this.$help, this.$field ); } // Set classes. The following classes can be used here: // * oo-ui-fieldLayout-align-left // * oo-ui-fieldLayout-align-right // * oo-ui-fieldLayout-align-top // * oo-ui-fieldLayout-align-inline if ( this.align ) { this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align ); } this.$element.addClass( 'oo-ui-fieldLayout-align-' + value ); this.align = value; } return this; }; /** * Set the list of error messages. * * @param {Array} errors Error messages about the widget, which will be displayed below the widget. * The array may contain strings or OO.ui.HtmlSnippet instances. * @chainable */ OO.ui.FieldLayout.prototype.setErrors = function ( errors ) { this.errors = errors.slice(); this.updateMessages(); return this; }; /** * Set the list of notice messages. * * @param {Array} notices Notices about the widget, which will be displayed below the widget. * The array may contain strings or OO.ui.HtmlSnippet instances. * @chainable */ OO.ui.FieldLayout.prototype.setNotices = function ( notices ) { this.notices = notices.slice(); this.updateMessages(); return this; }; /** * Update the rendering of error and notice messages. * * @private */ OO.ui.FieldLayout.prototype.updateMessages = function () { var i; this.$messages.empty(); if ( this.errors.length || this.notices.length ) { this.$body.after( this.$messages ); } else { this.$messages.remove(); return; } for ( i = 0; i < this.notices.length; i++ ) { this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) ); } for ( i = 0; i < this.errors.length; i++ ) { this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) ); } }; /** * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button, * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}), * is required and is specified before any optional configuration settings. * * Labels can be aligned in one of four ways: * * - **left**: The label is placed before the field-widget and aligned with the left margin. * A left-alignment is used for forms with many fields. * - **right**: The label is placed before the field-widget and aligned to the right margin. * A right-alignment is used for long but familiar forms which users tab through, * verifying the current field with a quick glance at the label. * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms * that users fill out from top to bottom. * - **inline**: The label is placed after the field-widget and aligned to the left. * An inline-alignment is best used with checkboxes or radio buttons. * * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help * text is specified. * * @example * // Example of an ActionFieldLayout * var actionFieldLayout = new OO.ui.ActionFieldLayout( * new OO.ui.TextInputWidget( { * placeholder: 'Field widget' * } ), * new OO.ui.ButtonWidget( { * label: 'Button' * } ), * { * label: 'An ActionFieldLayout. This label is aligned top', * align: 'top', * help: 'This is help text' * } * ); * * $( 'body' ).append( actionFieldLayout.$element ); * * @class * @extends OO.ui.FieldLayout * * @constructor * @param {OO.ui.Widget} fieldWidget Field widget * @param {OO.ui.ButtonWidget} buttonWidget Button widget * @param {Object} config */ OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( fieldWidget ) && config === undefined ) { config = fieldWidget; fieldWidget = config.fieldWidget; buttonWidget = config.buttonWidget; } // Parent constructor OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config ); // Properties this.buttonWidget = buttonWidget; this.$button = $( '<div>' ); this.$input = $( '<div>' ); // Initialization this.$element .addClass( 'oo-ui-actionFieldLayout' ); this.$button .addClass( 'oo-ui-actionFieldLayout-button' ) .append( this.buttonWidget.$element ); this.$input .addClass( 'oo-ui-actionFieldLayout-input' ) .append( this.fieldWidget.$element ); this.$field .append( this.$input, this.$button ); }; /* Setup */ OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout ); /** * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts}, * which each contain an individual widget and, optionally, a label. Each Fieldset can be * configured with a label as well. For more information and examples, * please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example of a fieldset layout * var input1 = new OO.ui.TextInputWidget( { * placeholder: 'A text input field' * } ); * * var input2 = new OO.ui.TextInputWidget( { * placeholder: 'A text input field' * } ); * * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Example of a fieldset layout' * } ); * * fieldset.addItems( [ * new OO.ui.FieldLayout( input1, { * label: 'Field One' * } ), * new OO.ui.FieldLayout( input2, { * label: 'Field Two' * } ) * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets * * @class * @extends OO.ui.Layout * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields. * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear * in the upper-right corner of the rendered field; clicking it will display the text in a popup. * For important messages, you are advised to use `notices`, as they are always shown. * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given. */ OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.FieldsetLayout.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: $( '<div>' ) } ) ); OO.ui.mixin.GroupElement.call( this, config ); // Properties this.$header = $( '<div>' ); if ( config.help ) { this.popupButtonWidget = new OO.ui.PopupButtonWidget( { $overlay: config.$overlay, popup: { padded: true }, classes: [ 'oo-ui-fieldsetLayout-help' ], framed: false, icon: 'info' } ); if ( config.help instanceof OO.ui.HtmlSnippet ) { this.popupButtonWidget.getPopup().$body.html( config.help.toString() ); } else { this.popupButtonWidget.getPopup().$body.text( config.help ); } this.$help = this.popupButtonWidget.$element; } else { this.$help = $( [] ); } // Initialization this.$header .addClass( 'oo-ui-fieldsetLayout-header' ) .append( this.$icon, this.$label, this.$help ); this.$group.addClass( 'oo-ui-fieldsetLayout-group' ); this.$element .addClass( 'oo-ui-fieldsetLayout' ) .prepend( this.$header, this.$group ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.FieldsetLayout.static.tagName = 'fieldset'; /** * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively. * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples. * * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as * some fancier controls. Some controls have both regular and InputWidget variants, for example * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and * often have simplified APIs to match the capabilities of HTML forms. * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @example * // Example of a form layout that wraps a fieldset layout * var input1 = new OO.ui.TextInputWidget( { * placeholder: 'Username' * } ); * var input2 = new OO.ui.TextInputWidget( { * placeholder: 'Password', * type: 'password' * } ); * var submit = new OO.ui.ButtonInputWidget( { * label: 'Submit' * } ); * * var fieldset = new OO.ui.FieldsetLayout( { * label: 'A form layout' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( input1, { * label: 'Username', * align: 'top' * } ), * new OO.ui.FieldLayout( input2, { * label: 'Password', * align: 'top' * } ), * new OO.ui.FieldLayout( submit ) * ] ); * var form = new OO.ui.FormLayout( { * items: [ fieldset ], * action: '/api/formhandler', * method: 'get' * } ) * $( 'body' ).append( form.$element ); * * @class * @extends OO.ui.Layout * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [method] HTML form `method` attribute * @cfg {string} [action] HTML form `action` attribute * @cfg {string} [enctype] HTML form `enctype` attribute * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout. */ OO.ui.FormLayout = function OoUiFormLayout( config ) { var action; // Configuration initialization config = config || {}; // Parent constructor OO.ui.FormLayout.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Events this.$element.on( 'submit', this.onFormSubmit.bind( this ) ); // Make sure the action is safe action = config.action; if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) { action = './' + action; } // Initialization this.$element .addClass( 'oo-ui-formLayout' ) .attr( { method: config.method, action: action, enctype: config.enctype } ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement ); /* Events */ /** * A 'submit' event is emitted when the form is submitted. * * @event submit */ /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.FormLayout.static.tagName = 'form'; /* Methods */ /** * Handle form submit events. * * @private * @param {jQuery.Event} e Submit event * @fires submit */ OO.ui.FormLayout.prototype.onFormSubmit = function () { if ( this.emit( 'submit' ) ) { return false; } }; /** * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding, * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}. * * @example * // Example of a panel layout * var panel = new OO.ui.PanelLayout( { * expanded: false, * framed: true, * padded: true, * $content: $( '<p>A panel layout with padding and a frame.</p>' ) * } ); * $( 'body' ).append( panel.$element ); * * @class * @extends OO.ui.Layout * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [scrollable=false] Allow vertical scrolling * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel. * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element. * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content. */ OO.ui.PanelLayout = function OoUiPanelLayout( config ) { // Configuration initialization config = $.extend( { scrollable: false, padded: false, expanded: true, framed: false }, config ); // Parent constructor OO.ui.PanelLayout.parent.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-panelLayout' ); if ( config.scrollable ) { this.$element.addClass( 'oo-ui-panelLayout-scrollable' ); } if ( config.padded ) { this.$element.addClass( 'oo-ui-panelLayout-padded' ); } if ( config.expanded ) { this.$element.addClass( 'oo-ui-panelLayout-expanded' ); } if ( config.framed ) { this.$element.addClass( 'oo-ui-panelLayout-framed' ); } }; /* Setup */ OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout ); /* Methods */ /** * Focus the panel layout * * The default implementation just focuses the first focusable element in the panel */ OO.ui.PanelLayout.prototype.focus = function () { OO.ui.findFocusable( this.$element ).focus(); }; /** * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its * items), with small margins between them. Convenient when you need to put a number of block-level * widgets on a single line next to each other. * * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper. * * @example * // HorizontalLayout with a text input and a label * var layout = new OO.ui.HorizontalLayout( { * items: [ * new OO.ui.LabelWidget( { label: 'Label' } ), * new OO.ui.TextInputWidget( { value: 'Text' } ) * ] * } ); * $( 'body' ).append( layout.$element ); * * @class * @extends OO.ui.Layout * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout. */ OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.HorizontalLayout.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-horizontalLayout' ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement ); }( OO ) ); //# sourceMappingURL=oojs-ui-core.js.map /*! * OOjs UI v0.19.3-pre (72b81a54a7) * https://www.mediawiki.org/wiki/OOjs_UI * * Copyright 2011–2017 OOjs UI Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2017-02-21T22:25:51Z */ ( function ( OO ) { 'use strict'; /** * DraggableElement is a mixin class used to create elements that can be clicked * and dragged by a mouse to a new position within a group. This class must be used * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for * the draggable elements. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$handle] The part of the element which can be used for dragging, defaults to the whole element */ OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement( config ) { config = config || {}; // Properties this.index = null; this.$handle = config.$handle || this.$element; this.wasHandleUsed = null; // Initialize and events this.$element.addClass( 'oo-ui-draggableElement' ) // We make the entire element draggable, not just the handle, so that // the whole element appears to move. wasHandleUsed prevents drags from // starting outside the handle .attr( 'draggable', true ) .on( { mousedown: this.onDragMouseDown.bind( this ), dragstart: this.onDragStart.bind( this ), dragover: this.onDragOver.bind( this ), dragend: this.onDragEnd.bind( this ), drop: this.onDrop.bind( this ) } ); this.$handle.addClass( 'oo-ui-draggableElement-handle' ); }; OO.initClass( OO.ui.mixin.DraggableElement ); /* Events */ /** * @event dragstart * * A dragstart event is emitted when the user clicks and begins dragging an item. * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse. */ /** * @event dragend * A dragend event is emitted when the user drags an item and releases the mouse, * thus terminating the drag operation. */ /** * @event drop * A drop event is emitted when the user drags an item and then releases the mouse button * over a valid target. */ /* Static Properties */ /** * @inheritdoc OO.ui.mixin.ButtonElement */ OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false; /* Methods */ /** * Respond to mousedown event. * * @private * @param {jQuery.Event} e Drag event */ OO.ui.mixin.DraggableElement.prototype.onDragMouseDown = function ( e ) { this.wasHandleUsed = // Optimization: if the handle is the whole element this is always true this.$handle[ 0 ] === this.$element[ 0 ] || // Check the mousedown occurred inside the handle OO.ui.contains( this.$handle[ 0 ], e.target, true ); }; /** * Respond to dragstart event. * * @private * @param {jQuery.Event} e Drag event * @return {boolean} False if the event is cancelled * @fires dragstart */ OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) { var element = this, dataTransfer = e.originalEvent.dataTransfer; if ( !this.wasHandleUsed ) { return false; } // Define drop effect dataTransfer.dropEffect = 'none'; dataTransfer.effectAllowed = 'move'; // Support: Firefox // We must set up a dataTransfer data property or Firefox seems to // ignore the fact the element is draggable. try { dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() ); } catch ( err ) { // The above is only for Firefox. Move on if it fails. } // Briefly add a 'clone' class to style the browser's native drag image this.$element.addClass( 'oo-ui-draggableElement-clone' ); // Add placeholder class after the browser has rendered the clone setTimeout( function () { element.$element .removeClass( 'oo-ui-draggableElement-clone' ) .addClass( 'oo-ui-draggableElement-placeholder' ); } ); // Emit event this.emit( 'dragstart', this ); return true; }; /** * Respond to dragend event. * * @private * @fires dragend */ OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () { this.$element.removeClass( 'oo-ui-draggableElement-placeholder' ); this.emit( 'dragend' ); }; /** * Handle drop event. * * @private * @param {jQuery.Event} e Drop event * @fires drop */ OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) { e.preventDefault(); this.emit( 'drop', e ); }; /** * In order for drag/drop to work, the dragover event must * return false and stop propogation. * * @param {jQuery.Event} e Drag event * @private */ OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) { e.preventDefault(); }; /** * Set item index. * Store it in the DOM so we can access from the widget drag event * * @private * @param {number} index Item index */ OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) { if ( this.index !== index ) { this.index = index; this.$element.data( 'index', index ); } }; /** * Get item index * * @private * @return {number} Item index */ OO.ui.mixin.DraggableElement.prototype.getIndex = function () { return this.index; }; /** * DraggableGroupElement is a mixin class used to create a group element to * contain draggable elements, which are items that can be clicked and dragged by a mouse. * The class is used with OO.ui.mixin.DraggableElement. * * @abstract * @class * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation * should match the layout of the items. Items displayed in a single row * or in several rows should use horizontal orientation. The vertical orientation should only be * used when the items are displayed in a single column. Defaults to 'vertical' */ OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.mixin.GroupElement.call( this, config ); // Properties this.orientation = config.orientation || 'vertical'; this.dragItem = null; this.itemKeys = {}; this.dir = null; this.itemsOrder = null; // Events this.aggregate( { dragstart: 'itemDragStart', dragend: 'itemDragEnd', drop: 'itemDrop' } ); this.connect( this, { itemDragStart: 'onItemDragStart', itemDrop: 'onItemDropOrDragEnd', itemDragEnd: 'onItemDropOrDragEnd' } ); // Initialize if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } this.$element .addClass( 'oo-ui-draggableGroupElement' ) .attr( 'role', 'listbox' ) .append( this.$status ) .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' ); }; /* Setup */ OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement ); /* Events */ /** * An item has been dragged to a new position, but not yet dropped. * * @event drag * @param {OO.ui.mixin.DraggableElement} item Dragged item * @param {number} [newIndex] New index for the item */ /** * And item has been dropped at a new position. * * @event reorder * @param {OO.ui.mixin.DraggableElement} item Reordered item * @param {number} [newIndex] New index for the item */ /* Methods */ /** * Respond to item drag start event * * @private * @param {OO.ui.mixin.DraggableElement} item Dragged item */ OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) { // Make a shallow copy of this.items so we can re-order it during previews // without affecting the original array. this.itemsOrder = this.items.slice(); this.updateIndexes(); if ( this.orientation === 'horizontal' ) { // Calculate and cache directionality on drag start - it's a little // expensive and it shouldn't change while dragging. this.dir = this.$element.css( 'direction' ); } this.setDragItem( item ); }; /** * Update the index properties of the items */ OO.ui.mixin.DraggableGroupElement.prototype.updateIndexes = function () { var i, len; // Map the index of each object for ( i = 0, len = this.itemsOrder.length; i < len; i++ ) { this.itemsOrder[ i ].setIndex( i ); } }; /** * Handle drop or dragend event and switch the order of the items accordingly * * @private * @param {OO.ui.mixin.DraggableElement} item Dropped item */ OO.ui.mixin.DraggableGroupElement.prototype.onItemDropOrDragEnd = function () { var targetIndex, originalIndex, item = this.getDragItem(); // TODO: Figure out a way to configure a list of legally droppable // elements even if they are not yet in the list if ( item ) { originalIndex = this.items.indexOf( item ); // If the item has moved forward, add one to the index to account for the left shift targetIndex = item.getIndex() + ( item.getIndex() > originalIndex ? 1 : 0 ); if ( targetIndex !== originalIndex ) { this.reorder( this.getDragItem(), targetIndex ); this.emit( 'reorder', this.getDragItem(), targetIndex ); } this.updateIndexes(); } this.unsetDragItem(); // Return false to prevent propogation return false; }; /** * Respond to dragover event * * @private * @param {jQuery.Event} e Dragover event * @fires reorder */ OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) { var overIndex, targetIndex, item = this.getDragItem(), dragItemIndex = item.getIndex(); // Get the OptionWidget item we are dragging over overIndex = $( e.target ).closest( '.oo-ui-draggableElement' ).data( 'index' ); if ( overIndex !== undefined && overIndex !== dragItemIndex ) { targetIndex = overIndex + ( overIndex > dragItemIndex ? 1 : 0 ); if ( targetIndex > 0 ) { this.$group.children().eq( targetIndex - 1 ).after( item.$element ); } else { this.$group.prepend( item.$element ); } // Move item in itemsOrder array this.itemsOrder.splice( overIndex, 0, this.itemsOrder.splice( dragItemIndex, 1 )[ 0 ] ); this.updateIndexes(); this.emit( 'drag', item, targetIndex ); } // Prevent default e.preventDefault(); }; /** * Reorder the items in the group * * @param {OO.ui.mixin.DraggableElement} item Reordered item * @param {number} newIndex New index */ OO.ui.mixin.DraggableGroupElement.prototype.reorder = function ( item, newIndex ) { this.addItems( [ item ], newIndex ); }; /** * Set a dragged item * * @param {OO.ui.mixin.DraggableElement} item Dragged item */ OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) { if ( this.dragItem !== item ) { this.dragItem = item; this.$element.on( 'dragover', this.onDragOver.bind( this ) ); this.$element.addClass( 'oo-ui-draggableGroupElement-dragging' ); } }; /** * Unset the current dragged item */ OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () { if ( this.dragItem ) { this.dragItem = null; this.$element.off( 'dragover' ); this.$element.removeClass( 'oo-ui-draggableGroupElement-dragging' ); } }; /** * Get the item that is currently being dragged. * * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged */ OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () { return this.dragItem; }; /** * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as * the {@link OO.ui.mixin.LookupElement}. * * @class * @abstract * * @constructor */ OO.ui.mixin.RequestManager = function OoUiMixinRequestManager() { this.requestCache = {}; this.requestQuery = null; this.requestRequest = null; }; /* Setup */ OO.initClass( OO.ui.mixin.RequestManager ); /** * Get request results for the current query. * * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of * the done event. If the request was aborted to make way for a subsequent request, this promise * may not be rejected, depending on what jQuery feels like doing. */ OO.ui.mixin.RequestManager.prototype.getRequestData = function () { var widget = this, value = this.getRequestQuery(), deferred = $.Deferred(), ourRequest; this.abortRequest(); if ( Object.prototype.hasOwnProperty.call( this.requestCache, value ) ) { deferred.resolve( this.requestCache[ value ] ); } else { if ( this.pushPending ) { this.pushPending(); } this.requestQuery = value; ourRequest = this.requestRequest = this.getRequest(); ourRequest .always( function () { // We need to pop pending even if this is an old request, otherwise // the widget will remain pending forever. // TODO: this assumes that an aborted request will fail or succeed soon after // being aborted, or at least eventually. It would be nice if we could popPending() // at abort time, but only if we knew that we hadn't already called popPending() // for that request. if ( widget.popPending ) { widget.popPending(); } } ) .done( function ( response ) { // If this is an old request (and aborting it somehow caused it to still succeed), // ignore its success completely if ( ourRequest === widget.requestRequest ) { widget.requestQuery = null; widget.requestRequest = null; widget.requestCache[ value ] = widget.getRequestCacheDataFromResponse( response ); deferred.resolve( widget.requestCache[ value ] ); } } ) .fail( function () { // If this is an old request (or a request failing because it's being aborted), // ignore its failure completely if ( ourRequest === widget.requestRequest ) { widget.requestQuery = null; widget.requestRequest = null; deferred.reject(); } } ); } return deferred.promise(); }; /** * Abort the currently pending request, if any. * * @private */ OO.ui.mixin.RequestManager.prototype.abortRequest = function () { var oldRequest = this.requestRequest; if ( oldRequest ) { // First unset this.requestRequest to the fail handler will notice // that the request is no longer current this.requestRequest = null; this.requestQuery = null; oldRequest.abort(); } }; /** * Get the query to be made. * * @protected * @method * @abstract * @return {string} query to be used */ OO.ui.mixin.RequestManager.prototype.getRequestQuery = null; /** * Get a new request object of the current query value. * * @protected * @method * @abstract * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method */ OO.ui.mixin.RequestManager.prototype.getRequest = null; /** * Pre-process data returned by the request from #getRequest. * * The return value of this function will be cached, and any further queries for the given value * will use the cache rather than doing API requests. * * @protected * @method * @abstract * @param {Mixed} response Response from server * @return {Mixed} Cached result data */ OO.ui.mixin.RequestManager.prototype.getRequestCacheDataFromResponse = null; /** * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen * from the lookup menu, that value becomes the value of the input field. * * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then * re-enable lookups. * * See the [OOjs UI demos][1] for an example. * * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr * * @class * @abstract * @mixins OO.ui.mixin.RequestManager * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element. * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty. * By default, the lookup menu is not generated and displayed until the user begins to type. * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can * take it over into the input with simply pressing return) automatically or not. */ OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) { // Configuration initialization config = $.extend( { highlightFirst: true }, config ); // Mixin constructors OO.ui.mixin.RequestManager.call( this, config ); // Properties this.$overlay = config.$overlay || this.$element; this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( { widget: this, input: this, $container: config.$container || this.$element } ); this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false; this.lookupsDisabled = false; this.lookupInputFocused = false; this.lookupHighlightFirstItem = config.highlightFirst; // Events this.$input.on( { focus: this.onLookupInputFocus.bind( this ), blur: this.onLookupInputBlur.bind( this ), mousedown: this.onLookupInputMouseDown.bind( this ) } ); this.connect( this, { change: 'onLookupInputChange' } ); this.lookupMenu.connect( this, { toggle: 'onLookupMenuToggle', choose: 'onLookupMenuItemChoose' } ); // Initialization this.$element.addClass( 'oo-ui-lookupElement' ); this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' ); this.$overlay.append( this.lookupMenu.$element ); }; /* Setup */ OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager ); /* Methods */ /** * Handle input focus event. * * @protected * @param {jQuery.Event} e Input focus event */ OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () { this.lookupInputFocused = true; this.populateLookupMenu(); }; /** * Handle input blur event. * * @protected * @param {jQuery.Event} e Input blur event */ OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () { this.closeLookupMenu(); this.lookupInputFocused = false; }; /** * Handle input mouse down event. * * @protected * @param {jQuery.Event} e Input mouse down event */ OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () { // Only open the menu if the input was already focused. // This way we allow the user to open the menu again after closing it with Esc // by clicking in the input. Opening (and populating) the menu when initially // clicking into the input is handled by the focus handler. if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) { this.populateLookupMenu(); } }; /** * Handle input change event. * * @protected * @param {string} value New input value */ OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () { if ( this.lookupInputFocused ) { this.populateLookupMenu(); } }; /** * Handle the lookup menu being shown/hidden. * * @protected * @param {boolean} visible Whether the lookup menu is now visible. */ OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) { if ( !visible ) { // When the menu is hidden, abort any active request and clear the menu. // This has to be done here in addition to closeLookupMenu(), because // MenuSelectWidget will close itself when the user presses Esc. this.abortLookupRequest(); this.lookupMenu.clearItems(); } }; /** * Handle menu item 'choose' event, updating the text input value to the value of the clicked item. * * @protected * @param {OO.ui.MenuOptionWidget} item Selected item */ OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) { this.setValue( item.getData() ); }; /** * Get lookup menu. * * @private * @return {OO.ui.FloatingMenuSelectWidget} */ OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () { return this.lookupMenu; }; /** * Disable or re-enable lookups. * * When lookups are disabled, calls to #populateLookupMenu will be ignored. * * @param {boolean} disabled Disable lookups */ OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) { this.lookupsDisabled = !!disabled; }; /** * Open the menu. If there are no entries in the menu, this does nothing. * * @private * @chainable */ OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () { if ( !this.lookupMenu.isEmpty() ) { this.lookupMenu.toggle( true ); } return this; }; /** * Close the menu, empty it, and abort any pending request. * * @private * @chainable */ OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () { this.lookupMenu.toggle( false ); this.abortLookupRequest(); this.lookupMenu.clearItems(); return this; }; /** * Request menu items based on the input's current value, and when they arrive, * populate the menu with these items and show the menu. * * If lookups have been disabled with #setLookupsDisabled, this function does nothing. * * @private * @chainable */ OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () { var widget = this, value = this.getValue(); if ( this.lookupsDisabled || this.isReadOnly() ) { return; } // If the input is empty, clear the menu, unless suggestions when empty are allowed. if ( !this.allowSuggestionsWhenEmpty && value === '' ) { this.closeLookupMenu(); // Skip population if there is already a request pending for the current value } else if ( value !== this.lookupQuery ) { this.getLookupMenuItems() .done( function ( items ) { widget.lookupMenu.clearItems(); if ( items.length ) { widget.lookupMenu .addItems( items ) .toggle( true ); widget.initializeLookupMenuSelection(); } else { widget.lookupMenu.toggle( false ); } } ) .fail( function () { widget.lookupMenu.clearItems(); } ); } return this; }; /** * Highlight the first selectable item in the menu, if configured. * * @private * @chainable */ OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () { if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) { this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() ); } }; /** * Get lookup menu items for the current query. * * @private * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of * the done event. If the request was aborted to make way for a subsequent request, this promise * will not be rejected: it will remain pending forever. */ OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () { return this.getRequestData().then( function ( data ) { return this.getLookupMenuOptionsFromData( data ); }.bind( this ) ); }; /** * Abort the currently pending lookup request, if any. * * @private */ OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () { this.abortRequest(); }; /** * Get a new request object of the current lookup query value. * * @protected * @method * @abstract * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method */ OO.ui.mixin.LookupElement.prototype.getLookupRequest = null; /** * Pre-process data returned by the request from #getLookupRequest. * * The return value of this function will be cached, and any further queries for the given value * will use the cache rather than doing API requests. * * @protected * @method * @abstract * @param {Mixed} response Response from server * @return {Mixed} Cached result data */ OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null; /** * Get a list of menu option widgets from the (possibly cached) data returned by * #getLookupCacheDataFromResponse. * * @protected * @method * @abstract * @param {Mixed} data Cached result data, usually an array * @return {OO.ui.MenuOptionWidget[]} Menu items */ OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null; /** * Set the read-only state of the widget. * * This will also disable/enable the lookups functionality. * * @param {boolean} readOnly Make input read-only * @chainable */ OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) { // Parent method // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly ); // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor if ( this.isReadOnly() && this.lookupMenu ) { this.closeLookupMenu(); } return this; }; /** * @inheritdoc OO.ui.mixin.RequestManager */ OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () { return this.getValue(); }; /** * @inheritdoc OO.ui.mixin.RequestManager */ OO.ui.mixin.LookupElement.prototype.getRequest = function () { return this.getLookupRequest(); }; /** * @inheritdoc OO.ui.mixin.RequestManager */ OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) { return this.getLookupCacheDataFromResponse( response ); }; /** * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly, * rather extended to include the required content and functionality. * * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab * item is customized (with a label) using the #setupTabItem method. See * {@link OO.ui.IndexLayout IndexLayout} for an example. * * @class * @extends OO.ui.PanelLayout * * @constructor * @param {string} name Unique symbolic name of card * @param {Object} [config] Configuration options * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab */ OO.ui.CardLayout = function OoUiCardLayout( name, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( name ) && config === undefined ) { config = name; name = config.name; } // Configuration initialization config = $.extend( { scrollable: true }, config ); // Parent constructor OO.ui.CardLayout.parent.call( this, config ); // Properties this.name = name; this.label = config.label; this.tabItem = null; this.active = false; // Initialization this.$element.addClass( 'oo-ui-cardLayout' ); }; /* Setup */ OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout ); /* Events */ /** * An 'active' event is emitted when the card becomes active. Cards become active when they are * shown in a index layout that is configured to display only one card at a time. * * @event active * @param {boolean} active Card is active */ /* Methods */ /** * Get the symbolic name of the card. * * @return {string} Symbolic name of card */ OO.ui.CardLayout.prototype.getName = function () { return this.name; }; /** * Check if card is active. * * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state. * * @return {boolean} Card is active */ OO.ui.CardLayout.prototype.isActive = function () { return this.active; }; /** * Get tab item. * * The tab item allows users to access the card from the index's tab * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method. * * @return {OO.ui.TabOptionWidget|null} Tab option widget */ OO.ui.CardLayout.prototype.getTabItem = function () { return this.tabItem; }; /** * Set or unset the tab item. * * Specify a {@link OO.ui.TabOptionWidget tab option} to set it, * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab * level), use #setupTabItem instead of this method. * * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear * @chainable */ OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) { this.tabItem = tabItem || null; if ( tabItem ) { this.setupTabItem(); } return this; }; /** * Set up the tab item. * * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use * the #setTabItem method instead. * * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up * @chainable */ OO.ui.CardLayout.prototype.setupTabItem = function () { if ( this.label ) { this.tabItem.setLabel( this.label ); } return this; }; /** * Set the card to its 'active' state. * * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional * CSS is applied to the tab item to reflect the card's active state. Outside of the index * context, setting the active state on a card does nothing. * * @param {boolean} active Card is active * @fires active */ OO.ui.CardLayout.prototype.setActive = function ( active ) { active = !!active; if ( active !== this.active ) { this.active = active; this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active ); this.emit( 'active', this.active ); } }; /** * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly, * rather extended to include the required content and functionality. * * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See * {@link OO.ui.BookletLayout BookletLayout} for an example. * * @class * @extends OO.ui.PanelLayout * * @constructor * @param {string} name Unique symbolic name of page * @param {Object} [config] Configuration options */ OO.ui.PageLayout = function OoUiPageLayout( name, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( name ) && config === undefined ) { config = name; name = config.name; } // Configuration initialization config = $.extend( { scrollable: true }, config ); // Parent constructor OO.ui.PageLayout.parent.call( this, config ); // Properties this.name = name; this.outlineItem = null; this.active = false; // Initialization this.$element.addClass( 'oo-ui-pageLayout' ); }; /* Setup */ OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout ); /* Events */ /** * An 'active' event is emitted when the page becomes active. Pages become active when they are * shown in a booklet layout that is configured to display only one page at a time. * * @event active * @param {boolean} active Page is active */ /* Methods */ /** * Get the symbolic name of the page. * * @return {string} Symbolic name of page */ OO.ui.PageLayout.prototype.getName = function () { return this.name; }; /** * Check if page is active. * * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state. * * @return {boolean} Page is active */ OO.ui.PageLayout.prototype.isActive = function () { return this.active; }; /** * Get outline item. * * The outline item allows users to access the page from the booklet's outline * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method. * * @return {OO.ui.OutlineOptionWidget|null} Outline option widget */ OO.ui.PageLayout.prototype.getOutlineItem = function () { return this.outlineItem; }; /** * Set or unset the outline item. * * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it, * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline * level), use #setupOutlineItem instead of this method. * * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear * @chainable */ OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) { this.outlineItem = outlineItem || null; if ( outlineItem ) { this.setupOutlineItem(); } return this; }; /** * Set up the outline item. * * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use * the #setOutlineItem method instead. * * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up * @chainable */ OO.ui.PageLayout.prototype.setupOutlineItem = function () { return this; }; /** * Set the page to its 'active' state. * * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet * context, setting the active state on a page does nothing. * * @param {boolean} active Page is active * @fires active */ OO.ui.PageLayout.prototype.setActive = function ( active ) { active = !!active; if ( active !== this.active ) { this.active = active; this.$element.toggleClass( 'oo-ui-pageLayout-active', active ); this.emit( 'active', this.active ); } }; /** * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed * at a time, though the stack layout can also be configured to show all contained panels, one after another, * by setting the #continuous option to 'true'. * * @example * // A stack layout with two panels, configured to be displayed continously * var myStack = new OO.ui.StackLayout( { * items: [ * new OO.ui.PanelLayout( { * $content: $( '<p>Panel One</p>' ), * padded: true, * framed: true * } ), * new OO.ui.PanelLayout( { * $content: $( '<p>Panel Two</p>' ), * padded: true, * framed: true * } ) * ], * continuous: true * } ); * $( 'body' ).append( myStack.$element ); * * @class * @extends OO.ui.PanelLayout * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time. * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout. */ OO.ui.StackLayout = function OoUiStackLayout( config ) { // Configuration initialization config = $.extend( { scrollable: true }, config ); // Parent constructor OO.ui.StackLayout.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Properties this.currentItem = null; this.continuous = !!config.continuous; // Initialization this.$element.addClass( 'oo-ui-stackLayout' ); if ( this.continuous ) { this.$element.addClass( 'oo-ui-stackLayout-continuous' ); this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) ); } if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout ); OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement ); /* Events */ /** * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed}, * {@link #clearItems cleared} or {@link #setItem displayed}. * * @event set * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown */ /** * When used in continuous mode, this event is emitted when the user scrolls down * far enough such that currentItem is no longer visible. * * @event visibleItemChange * @param {OO.ui.PanelLayout} panel The next visible item in the layout */ /* Methods */ /** * Handle scroll events from the layout element * * @param {jQuery.Event} e * @fires visibleItemChange */ OO.ui.StackLayout.prototype.onScroll = function () { var currentRect, len = this.items.length, currentIndex = this.items.indexOf( this.currentItem ), newIndex = currentIndex, containerRect = this.$element[ 0 ].getBoundingClientRect(); if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) { // Can't get bounding rect, possibly not attached. return; } function getRect( item ) { return item.$element[ 0 ].getBoundingClientRect(); } function isVisible( item ) { var rect = getRect( item ); return rect.bottom > containerRect.top && rect.top < containerRect.bottom; } currentRect = getRect( this.currentItem ); if ( currentRect.bottom < containerRect.top ) { // Scrolled down past current item while ( ++newIndex < len ) { if ( isVisible( this.items[ newIndex ] ) ) { break; } } } else if ( currentRect.top > containerRect.bottom ) { // Scrolled up past current item while ( --newIndex >= 0 ) { if ( isVisible( this.items[ newIndex ] ) ) { break; } } } if ( newIndex !== currentIndex ) { this.emit( 'visibleItemChange', this.items[ newIndex ] ); } }; /** * Get the current panel. * * @return {OO.ui.Layout|null} */ OO.ui.StackLayout.prototype.getCurrentItem = function () { return this.currentItem; }; /** * Unset the current item. * * @private * @param {OO.ui.StackLayout} layout * @fires set */ OO.ui.StackLayout.prototype.unsetCurrentItem = function () { var prevItem = this.currentItem; if ( prevItem === null ) { return; } this.currentItem = null; this.emit( 'set', null ); }; /** * Add panel layouts to the stack layout. * * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified * by the index. * * @param {OO.ui.Layout[]} items Panels to add * @param {number} [index] Index of the insertion point * @chainable */ OO.ui.StackLayout.prototype.addItems = function ( items, index ) { // Update the visibility this.updateHiddenState( items, this.currentItem ); // Mixin method OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index ); if ( !this.currentItem && items.length ) { this.setItem( items[ 0 ] ); } return this; }; /** * Remove the specified panels from the stack layout. * * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels, * you may wish to use the #clearItems method instead. * * @param {OO.ui.Layout[]} items Panels to remove * @chainable * @fires set */ OO.ui.StackLayout.prototype.removeItems = function ( items ) { // Mixin method OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items ); if ( items.indexOf( this.currentItem ) !== -1 ) { if ( this.items.length ) { this.setItem( this.items[ 0 ] ); } else { this.unsetCurrentItem(); } } return this; }; /** * Clear all panels from the stack layout. * * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only * a subset of panels, use the #removeItems method. * * @chainable * @fires set */ OO.ui.StackLayout.prototype.clearItems = function () { this.unsetCurrentItem(); OO.ui.mixin.GroupElement.prototype.clearItems.call( this ); return this; }; /** * Show the specified panel. * * If another panel is currently displayed, it will be hidden. * * @param {OO.ui.Layout} item Panel to show * @chainable * @fires set */ OO.ui.StackLayout.prototype.setItem = function ( item ) { if ( item !== this.currentItem ) { this.updateHiddenState( this.items, item ); if ( this.items.indexOf( item ) !== -1 ) { this.currentItem = item; this.emit( 'set', item ); } else { this.unsetCurrentItem(); } } return this; }; /** * Update the visibility of all items in case of non-continuous view. * * Ensure all items are hidden except for the selected one. * This method does nothing when the stack is continuous. * * @private * @param {OO.ui.Layout[]} items Item list iterate over * @param {OO.ui.Layout} [selectedItem] Selected item to show */ OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) { var i, len; if ( !this.continuous ) { for ( i = 0, len = items.length; i < len; i++ ) { if ( !selectedItem || selectedItem !== items[ i ] ) { items[ i ].$element.addClass( 'oo-ui-element-hidden' ); items[ i ].$element.attr( 'aria-hidden', 'true' ); } } if ( selectedItem ) { selectedItem.$element.removeClass( 'oo-ui-element-hidden' ); selectedItem.$element.removeAttr( 'aria-hidden' ); } } }; /** * MenuLayouts combine a menu and a content {@link OO.ui.PanelLayout panel}. The menu is positioned relative to the content (after, before, top, or bottom) * and its size is customized with the #menuSize config. The content area will fill all remaining space. * * @example * var menuLayout = new OO.ui.MenuLayout( { * position: 'top' * } ), * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ), * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ), * select = new OO.ui.SelectWidget( { * items: [ * new OO.ui.OptionWidget( { * data: 'before', * label: 'Before', * } ), * new OO.ui.OptionWidget( { * data: 'after', * label: 'After', * } ), * new OO.ui.OptionWidget( { * data: 'top', * label: 'Top', * } ), * new OO.ui.OptionWidget( { * data: 'bottom', * label: 'Bottom', * } ) * ] * } ).on( 'select', function ( item ) { * menuLayout.setMenuPosition( item.getData() ); * } ); * * menuLayout.$menu.append( * menuPanel.$element.append( '<b>Menu panel</b>', select.$element ) * ); * menuLayout.$content.append( * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>') * ); * $( 'body' ).append( menuLayout.$element ); * * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions * may be omitted. * * .oo-ui-menuLayout-menu { * height: 200px; * width: 200px; * } * .oo-ui-menuLayout-content { * top: 200px; * left: 200px; * right: 200px; * bottom: 200px; * } * * @class * @extends OO.ui.Layout * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [showMenu=true] Show menu * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before` */ OO.ui.MenuLayout = function OoUiMenuLayout( config ) { // Configuration initialization config = $.extend( { showMenu: true, menuPosition: 'before' }, config ); // Parent constructor OO.ui.MenuLayout.parent.call( this, config ); /** * Menu DOM node * * @property {jQuery} */ this.$menu = $( '<div>' ); /** * Content DOM node * * @property {jQuery} */ this.$content = $( '<div>' ); // Initialization this.$menu .addClass( 'oo-ui-menuLayout-menu' ); this.$content.addClass( 'oo-ui-menuLayout-content' ); this.$element .addClass( 'oo-ui-menuLayout' ) .append( this.$content, this.$menu ); this.setMenuPosition( config.menuPosition ); this.toggleMenu( config.showMenu ); }; /* Setup */ OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout ); /* Methods */ /** * Toggle menu. * * @param {boolean} showMenu Show menu, omit to toggle * @chainable */ OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) { showMenu = showMenu === undefined ? !this.showMenu : !!showMenu; if ( this.showMenu !== showMenu ) { this.showMenu = showMenu; this.$element .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu ) .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu ); this.$menu.attr( 'aria-hidden', this.showMenu ? 'false' : 'true' ); } return this; }; /** * Check if menu is visible * * @return {boolean} Menu is visible */ OO.ui.MenuLayout.prototype.isMenuVisible = function () { return this.showMenu; }; /** * Set menu position. * * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before` * @throws {Error} If position value is not supported * @chainable */ OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) { this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition ); this.menuPosition = position; this.$element.addClass( 'oo-ui-menuLayout-' + position ); return this; }; /** * Get menu position. * * @return {string} Menu position */ OO.ui.MenuLayout.prototype.getMenuPosition = function () { return this.menuPosition; }; /** * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate * through the pages and select which one to display. By default, only one page is * displayed at a time and the outline is hidden. When a user navigates to a new page, * the booklet layout automatically focuses on the first focusable element, unless the * default setting is changed. Optionally, booklets can be configured to show * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items. * * @example * // Example of a BookletLayout that contains two PageLayouts. * * function PageOneLayout( name, config ) { * PageOneLayout.parent.call( this, name, config ); * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' ); * } * OO.inheritClass( PageOneLayout, OO.ui.PageLayout ); * PageOneLayout.prototype.setupOutlineItem = function () { * this.outlineItem.setLabel( 'Page One' ); * }; * * function PageTwoLayout( name, config ) { * PageTwoLayout.parent.call( this, name, config ); * this.$element.append( '<p>Second page</p>' ); * } * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout ); * PageTwoLayout.prototype.setupOutlineItem = function () { * this.outlineItem.setLabel( 'Page Two' ); * }; * * var page1 = new PageOneLayout( 'one' ), * page2 = new PageTwoLayout( 'two' ); * * var booklet = new OO.ui.BookletLayout( { * outlined: true * } ); * * booklet.addPages ( [ page1, page2 ] ); * $( 'body' ).append( booklet.$element ); * * @class * @extends OO.ui.MenuLayout * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [continuous=false] Show all pages, one after another * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed. Disabled on mobile. * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet. * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages */ OO.ui.BookletLayout = function OoUiBookletLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.BookletLayout.parent.call( this, config ); // Properties this.currentPageName = null; this.pages = {}; this.ignoreFocus = false; this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } ); this.$content.append( this.stackLayout.$element ); this.autoFocus = config.autoFocus === undefined || !!config.autoFocus; this.outlineVisible = false; this.outlined = !!config.outlined; if ( this.outlined ) { this.editable = !!config.editable; this.outlineControlsWidget = null; this.outlineSelectWidget = new OO.ui.OutlineSelectWidget(); this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } ); this.$menu.append( this.outlinePanel.$element ); this.outlineVisible = true; if ( this.editable ) { this.outlineControlsWidget = new OO.ui.OutlineControlsWidget( this.outlineSelectWidget ); } } this.toggleMenu( this.outlined ); // Events this.stackLayout.connect( this, { set: 'onStackLayoutSet' } ); if ( this.outlined ) { this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } ); this.scrolling = false; this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } ); } if ( this.autoFocus ) { // Event 'focus' does not bubble, but 'focusin' does this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) ); } // Initialization this.$element.addClass( 'oo-ui-bookletLayout' ); this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' ); if ( this.outlined ) { this.outlinePanel.$element .addClass( 'oo-ui-bookletLayout-outlinePanel' ) .append( this.outlineSelectWidget.$element ); if ( this.editable ) { this.outlinePanel.$element .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' ) .append( this.outlineControlsWidget.$element ); } } }; /* Setup */ OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout ); /* Events */ /** * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout. * @event set * @param {OO.ui.PageLayout} page Current page */ /** * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout. * * @event add * @param {OO.ui.PageLayout[]} page Added pages * @param {number} index Index pages were added at */ /** * A 'remove' event is emitted when pages are {@link #clearPages cleared} or * {@link #removePages removed} from the booklet. * * @event remove * @param {OO.ui.PageLayout[]} pages Removed pages */ /* Methods */ /** * Handle stack layout focus. * * @private * @param {jQuery.Event} e Focusin event */ OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) { var name, $target; // Find the page that an element was focused within $target = $( e.target ).closest( '.oo-ui-pageLayout' ); for ( name in this.pages ) { // Check for page match, exclude current page to find only page changes if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) { this.setPage( name ); break; } } }; /** * Handle visibleItemChange events from the stackLayout * * The next visible page is set as the current page by selecting it * in the outline * * @param {OO.ui.PageLayout} page The next visible page in the layout */ OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) { // Set a flag to so that the resulting call to #onStackLayoutSet doesn't // try and scroll the item into view again. this.scrolling = true; this.outlineSelectWidget.selectItemByData( page.getName() ); this.scrolling = false; }; /** * Handle stack layout set events. * * @private * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel */ OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) { var layout = this; if ( !this.scrolling && page ) { page.scrollElementIntoView().done( function () { if ( layout.autoFocus && !OO.ui.isMobile() ) { layout.focus(); } } ); } }; /** * Focus the first input in the current page. * * If no page is selected, the first selectable page will be selected. * If the focus is already in an element on the current page, nothing will happen. * * @param {number} [itemIndex] A specific item to focus on */ OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) { var page, items = this.stackLayout.getItems(); if ( itemIndex !== undefined && items[ itemIndex ] ) { page = items[ itemIndex ]; } else { page = this.stackLayout.getCurrentItem(); } if ( !page && this.outlined ) { this.selectFirstSelectablePage(); page = this.stackLayout.getCurrentItem(); } if ( !page ) { return; } // Only change the focus if is not already in the current page if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) { page.focus(); } }; /** * Find the first focusable input in the booklet layout and focus * on it. */ OO.ui.BookletLayout.prototype.focusFirstFocusable = function () { OO.ui.findFocusable( this.stackLayout.$element ).focus(); }; /** * Handle outline widget select events. * * @private * @param {OO.ui.OptionWidget|null} item Selected item */ OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) { if ( item ) { this.setPage( item.getData() ); } }; /** * Check if booklet has an outline. * * @return {boolean} Booklet has an outline */ OO.ui.BookletLayout.prototype.isOutlined = function () { return this.outlined; }; /** * Check if booklet has editing controls. * * @return {boolean} Booklet is editable */ OO.ui.BookletLayout.prototype.isEditable = function () { return this.editable; }; /** * Check if booklet has a visible outline. * * @return {boolean} Outline is visible */ OO.ui.BookletLayout.prototype.isOutlineVisible = function () { return this.outlined && this.outlineVisible; }; /** * Hide or show the outline. * * @param {boolean} [show] Show outline, omit to invert current state * @chainable */ OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) { if ( this.outlined ) { show = show === undefined ? !this.outlineVisible : !!show; this.outlineVisible = show; this.toggleMenu( show ); } return this; }; /** * Get the page closest to the specified page. * * @param {OO.ui.PageLayout} page Page to use as a reference point * @return {OO.ui.PageLayout|null} Page closest to the specified page */ OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) { var next, prev, level, pages = this.stackLayout.getItems(), index = pages.indexOf( page ); if ( index !== -1 ) { next = pages[ index + 1 ]; prev = pages[ index - 1 ]; // Prefer adjacent pages at the same level if ( this.outlined ) { level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel(); if ( prev && level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel() ) { return prev; } if ( next && level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel() ) { return next; } } } return prev || next || null; }; /** * Get the outline widget. * * If the booklet is not outlined, the method will return `null`. * * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined */ OO.ui.BookletLayout.prototype.getOutline = function () { return this.outlineSelectWidget; }; /** * Get the outline controls widget. * * If the outline is not editable, the method will return `null`. * * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget. */ OO.ui.BookletLayout.prototype.getOutlineControls = function () { return this.outlineControlsWidget; }; /** * Get a page by its symbolic name. * * @param {string} name Symbolic name of page * @return {OO.ui.PageLayout|undefined} Page, if found */ OO.ui.BookletLayout.prototype.getPage = function ( name ) { return this.pages[ name ]; }; /** * Get the current page. * * @return {OO.ui.PageLayout|undefined} Current page, if found */ OO.ui.BookletLayout.prototype.getCurrentPage = function () { var name = this.getCurrentPageName(); return name ? this.getPage( name ) : undefined; }; /** * Get the symbolic name of the current page. * * @return {string|null} Symbolic name of the current page */ OO.ui.BookletLayout.prototype.getCurrentPageName = function () { return this.currentPageName; }; /** * Add pages to the booklet layout * * When pages are added with the same names as existing pages, the existing pages will be * automatically removed before the new pages are added. * * @param {OO.ui.PageLayout[]} pages Pages to add * @param {number} index Index of the insertion point * @fires add * @chainable */ OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) { var i, len, name, page, item, currentIndex, stackLayoutPages = this.stackLayout.getItems(), remove = [], items = []; // Remove pages with same names for ( i = 0, len = pages.length; i < len; i++ ) { page = pages[ i ]; name = page.getName(); if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) { // Correct the insertion index currentIndex = stackLayoutPages.indexOf( this.pages[ name ] ); if ( currentIndex !== -1 && currentIndex + 1 < index ) { index--; } remove.push( this.pages[ name ] ); } } if ( remove.length ) { this.removePages( remove ); } // Add new pages for ( i = 0, len = pages.length; i < len; i++ ) { page = pages[ i ]; name = page.getName(); this.pages[ page.getName() ] = page; if ( this.outlined ) { item = new OO.ui.OutlineOptionWidget( { data: name } ); page.setOutlineItem( item ); items.push( item ); } } if ( this.outlined && items.length ) { this.outlineSelectWidget.addItems( items, index ); this.selectFirstSelectablePage(); } this.stackLayout.addItems( pages, index ); this.emit( 'add', pages, index ); return this; }; /** * Remove the specified pages from the booklet layout. * * To remove all pages from the booklet, you may wish to use the #clearPages method instead. * * @param {OO.ui.PageLayout[]} pages An array of pages to remove * @fires remove * @chainable */ OO.ui.BookletLayout.prototype.removePages = function ( pages ) { var i, len, name, page, items = []; for ( i = 0, len = pages.length; i < len; i++ ) { page = pages[ i ]; name = page.getName(); delete this.pages[ name ]; if ( this.outlined ) { items.push( this.outlineSelectWidget.getItemFromData( name ) ); page.setOutlineItem( null ); } } if ( this.outlined && items.length ) { this.outlineSelectWidget.removeItems( items ); this.selectFirstSelectablePage(); } this.stackLayout.removeItems( pages ); this.emit( 'remove', pages ); return this; }; /** * Clear all pages from the booklet layout. * * To remove only a subset of pages from the booklet, use the #removePages method. * * @fires remove * @chainable */ OO.ui.BookletLayout.prototype.clearPages = function () { var i, len, pages = this.stackLayout.getItems(); this.pages = {}; this.currentPageName = null; if ( this.outlined ) { this.outlineSelectWidget.clearItems(); for ( i = 0, len = pages.length; i < len; i++ ) { pages[ i ].setOutlineItem( null ); } } this.stackLayout.clearItems(); this.emit( 'remove', pages ); return this; }; /** * Set the current page by symbolic name. * * @fires set * @param {string} name Symbolic name of page */ OO.ui.BookletLayout.prototype.setPage = function ( name ) { var selectedItem, $focused, page = this.pages[ name ], previousPage = this.currentPageName && this.pages[ this.currentPageName ]; if ( name !== this.currentPageName ) { if ( this.outlined ) { selectedItem = this.outlineSelectWidget.getSelectedItem(); if ( selectedItem && selectedItem.getData() !== name ) { this.outlineSelectWidget.selectItemByData( name ); } } if ( page ) { if ( previousPage ) { previousPage.setActive( false ); // Blur anything focused if the next page doesn't have anything focusable. // This is not needed if the next page has something focusable (because once it is focused // this blur happens automatically). If the layout is non-continuous, this check is // meaningless because the next page is not visible yet and thus can't hold focus. if ( this.autoFocus && !OO.ui.isMobile() && this.stackLayout.continuous && OO.ui.findFocusable( page.$element ).length !== 0 ) { $focused = previousPage.$element.find( ':focus' ); if ( $focused.length ) { $focused[ 0 ].blur(); } } } this.currentPageName = name; page.setActive( true ); this.stackLayout.setItem( page ); if ( !this.stackLayout.continuous && previousPage ) { // This should not be necessary, since any inputs on the previous page should have been // blurred when it was hidden, but browsers are not very consistent about this. $focused = previousPage.$element.find( ':focus' ); if ( $focused.length ) { $focused[ 0 ].blur(); } } this.emit( 'set', page ); } } }; /** * Select the first selectable page. * * @chainable */ OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () { if ( !this.outlineSelectWidget.getSelectedItem() ) { this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() ); } return this; }; /** * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and * select which one to display. By default, only one card is displayed at a time. When a user * navigates to a new card, the index layout automatically focuses on the first focusable element, * unless the default setting is changed. * * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication * * @example * // Example of a IndexLayout that contains two CardLayouts. * * function CardOneLayout( name, config ) { * CardOneLayout.parent.call( this, name, config ); * this.$element.append( '<p>First card</p>' ); * } * OO.inheritClass( CardOneLayout, OO.ui.CardLayout ); * CardOneLayout.prototype.setupTabItem = function () { * this.tabItem.setLabel( 'Card one' ); * }; * * var card1 = new CardOneLayout( 'one' ), * card2 = new OO.ui.CardLayout( 'two', { label: 'Card two' } ); * * card2.$element.append( '<p>Second card</p>' ); * * var index = new OO.ui.IndexLayout(); * * index.addCards ( [ card1, card2 ] ); * $( 'body' ).append( index.$element ); * * @class * @extends OO.ui.MenuLayout * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [continuous=false] Show all cards, one after another * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element. * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed. Disabled on mobile. */ OO.ui.IndexLayout = function OoUiIndexLayout( config ) { // Configuration initialization config = $.extend( {}, config, { menuPosition: 'top' } ); // Parent constructor OO.ui.IndexLayout.parent.call( this, config ); // Properties this.currentCardName = null; this.cards = {}; this.ignoreFocus = false; this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous, expanded: config.expanded } ); this.$content.append( this.stackLayout.$element ); this.autoFocus = config.autoFocus === undefined || !!config.autoFocus; this.tabSelectWidget = new OO.ui.TabSelectWidget(); this.tabPanel = new OO.ui.PanelLayout(); this.$menu.append( this.tabPanel.$element ); this.toggleMenu( true ); // Events this.stackLayout.connect( this, { set: 'onStackLayoutSet' } ); this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } ); if ( this.autoFocus ) { // Event 'focus' does not bubble, but 'focusin' does this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) ); } // Initialization this.$element.addClass( 'oo-ui-indexLayout' ); this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' ); this.tabPanel.$element .addClass( 'oo-ui-indexLayout-tabPanel' ) .append( this.tabSelectWidget.$element ); }; /* Setup */ OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout ); /* Events */ /** * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout. * @event set * @param {OO.ui.CardLayout} card Current card */ /** * An 'add' event is emitted when cards are {@link #addCards added} to the index layout. * * @event add * @param {OO.ui.CardLayout[]} card Added cards * @param {number} index Index cards were added at */ /** * A 'remove' event is emitted when cards are {@link #clearCards cleared} or * {@link #removeCards removed} from the index. * * @event remove * @param {OO.ui.CardLayout[]} cards Removed cards */ /* Methods */ /** * Handle stack layout focus. * * @private * @param {jQuery.Event} e Focusin event */ OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) { var name, $target; // Find the card that an element was focused within $target = $( e.target ).closest( '.oo-ui-cardLayout' ); for ( name in this.cards ) { // Check for card match, exclude current card to find only card changes if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) { this.setCard( name ); break; } } }; /** * Handle stack layout set events. * * @private * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel */ OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) { var layout = this; if ( card ) { card.scrollElementIntoView().done( function () { if ( layout.autoFocus && !OO.ui.isMobile() ) { layout.focus(); } } ); } }; /** * Focus the first input in the current card. * * If no card is selected, the first selectable card will be selected. * If the focus is already in an element on the current card, nothing will happen. * * @param {number} [itemIndex] A specific item to focus on */ OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) { var card, items = this.stackLayout.getItems(); if ( itemIndex !== undefined && items[ itemIndex ] ) { card = items[ itemIndex ]; } else { card = this.stackLayout.getCurrentItem(); } if ( !card ) { this.selectFirstSelectableCard(); card = this.stackLayout.getCurrentItem(); } if ( !card ) { return; } // Only change the focus if is not already in the current page if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) { card.focus(); } }; /** * Find the first focusable input in the index layout and focus * on it. */ OO.ui.IndexLayout.prototype.focusFirstFocusable = function () { OO.ui.findFocusable( this.stackLayout.$element ).focus(); }; /** * Handle tab widget select events. * * @private * @param {OO.ui.OptionWidget|null} item Selected item */ OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) { if ( item ) { this.setCard( item.getData() ); } }; /** * Get the card closest to the specified card. * * @param {OO.ui.CardLayout} card Card to use as a reference point * @return {OO.ui.CardLayout|null} Card closest to the specified card */ OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) { var next, prev, level, cards = this.stackLayout.getItems(), index = cards.indexOf( card ); if ( index !== -1 ) { next = cards[ index + 1 ]; prev = cards[ index - 1 ]; // Prefer adjacent cards at the same level level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel(); if ( prev && level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel() ) { return prev; } if ( next && level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel() ) { return next; } } return prev || next || null; }; /** * Get the tabs widget. * * @return {OO.ui.TabSelectWidget} Tabs widget */ OO.ui.IndexLayout.prototype.getTabs = function () { return this.tabSelectWidget; }; /** * Get a card by its symbolic name. * * @param {string} name Symbolic name of card * @return {OO.ui.CardLayout|undefined} Card, if found */ OO.ui.IndexLayout.prototype.getCard = function ( name ) { return this.cards[ name ]; }; /** * Get the current card. * * @return {OO.ui.CardLayout|undefined} Current card, if found */ OO.ui.IndexLayout.prototype.getCurrentCard = function () { var name = this.getCurrentCardName(); return name ? this.getCard( name ) : undefined; }; /** * Get the symbolic name of the current card. * * @return {string|null} Symbolic name of the current card */ OO.ui.IndexLayout.prototype.getCurrentCardName = function () { return this.currentCardName; }; /** * Add cards to the index layout * * When cards are added with the same names as existing cards, the existing cards will be * automatically removed before the new cards are added. * * @param {OO.ui.CardLayout[]} cards Cards to add * @param {number} index Index of the insertion point * @fires add * @chainable */ OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) { var i, len, name, card, item, currentIndex, stackLayoutCards = this.stackLayout.getItems(), remove = [], items = []; // Remove cards with same names for ( i = 0, len = cards.length; i < len; i++ ) { card = cards[ i ]; name = card.getName(); if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) { // Correct the insertion index currentIndex = stackLayoutCards.indexOf( this.cards[ name ] ); if ( currentIndex !== -1 && currentIndex + 1 < index ) { index--; } remove.push( this.cards[ name ] ); } } if ( remove.length ) { this.removeCards( remove ); } // Add new cards for ( i = 0, len = cards.length; i < len; i++ ) { card = cards[ i ]; name = card.getName(); this.cards[ card.getName() ] = card; item = new OO.ui.TabOptionWidget( { data: name } ); card.setTabItem( item ); items.push( item ); } if ( items.length ) { this.tabSelectWidget.addItems( items, index ); this.selectFirstSelectableCard(); } this.stackLayout.addItems( cards, index ); this.emit( 'add', cards, index ); return this; }; /** * Remove the specified cards from the index layout. * * To remove all cards from the index, you may wish to use the #clearCards method instead. * * @param {OO.ui.CardLayout[]} cards An array of cards to remove * @fires remove * @chainable */ OO.ui.IndexLayout.prototype.removeCards = function ( cards ) { var i, len, name, card, items = []; for ( i = 0, len = cards.length; i < len; i++ ) { card = cards[ i ]; name = card.getName(); delete this.cards[ name ]; items.push( this.tabSelectWidget.getItemFromData( name ) ); card.setTabItem( null ); } if ( items.length ) { this.tabSelectWidget.removeItems( items ); this.selectFirstSelectableCard(); } this.stackLayout.removeItems( cards ); this.emit( 'remove', cards ); return this; }; /** * Clear all cards from the index layout. * * To remove only a subset of cards from the index, use the #removeCards method. * * @fires remove * @chainable */ OO.ui.IndexLayout.prototype.clearCards = function () { var i, len, cards = this.stackLayout.getItems(); this.cards = {}; this.currentCardName = null; this.tabSelectWidget.clearItems(); for ( i = 0, len = cards.length; i < len; i++ ) { cards[ i ].setTabItem( null ); } this.stackLayout.clearItems(); this.emit( 'remove', cards ); return this; }; /** * Set the current card by symbolic name. * * @fires set * @param {string} name Symbolic name of card */ OO.ui.IndexLayout.prototype.setCard = function ( name ) { var selectedItem, $focused, card = this.cards[ name ], previousCard = this.currentCardName && this.cards[ this.currentCardName ]; if ( name !== this.currentCardName ) { selectedItem = this.tabSelectWidget.getSelectedItem(); if ( selectedItem && selectedItem.getData() !== name ) { this.tabSelectWidget.selectItemByData( name ); } if ( card ) { if ( previousCard ) { previousCard.setActive( false ); // Blur anything focused if the next card doesn't have anything focusable. // This is not needed if the next card has something focusable (because once it is focused // this blur happens automatically). If the layout is non-continuous, this check is // meaningless because the next card is not visible yet and thus can't hold focus. if ( this.autoFocus && !OO.ui.isMobile() && this.stackLayout.continuous && OO.ui.findFocusable( card.$element ).length !== 0 ) { $focused = previousCard.$element.find( ':focus' ); if ( $focused.length ) { $focused[ 0 ].blur(); } } } this.currentCardName = name; card.setActive( true ); this.stackLayout.setItem( card ); if ( !this.stackLayout.continuous && previousCard ) { // This should not be necessary, since any inputs on the previous card should have been // blurred when it was hidden, but browsers are not very consistent about this. $focused = previousCard.$element.find( ':focus' ); if ( $focused.length ) { $focused[ 0 ].blur(); } } this.emit( 'set', card ); } } }; /** * Select the first selectable card. * * @chainable */ OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () { if ( !this.tabSelectWidget.getSelectedItem() ) { this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() ); } return this; }; /** * ToggleWidget implements basic behavior of widgets with an on/off state. * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples. * * @abstract * @class * @extends OO.ui.Widget * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [value=false] The toggle’s initial on/off state. * By default, the toggle is in the 'off' state. */ OO.ui.ToggleWidget = function OoUiToggleWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ToggleWidget.parent.call( this, config ); // Properties this.value = null; // Initialization this.$element.addClass( 'oo-ui-toggleWidget' ); this.setValue( !!config.value ); }; /* Setup */ OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget ); /* Events */ /** * @event change * * A change event is emitted when the on/off state of the toggle changes. * * @param {boolean} value Value representing the new state of the toggle */ /* Methods */ /** * Get the value representing the toggle’s state. * * @return {boolean} The on/off state of the toggle */ OO.ui.ToggleWidget.prototype.getValue = function () { return this.value; }; /** * Set the state of the toggle: `true` for 'on', `false' for 'off'. * * @param {boolean} value The state of the toggle * @fires change * @chainable */ OO.ui.ToggleWidget.prototype.setValue = function ( value ) { value = !!value; if ( this.value !== value ) { this.value = value; this.emit( 'change', value ); this.$element.toggleClass( 'oo-ui-toggleWidget-on', value ); this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value ); this.$element.attr( 'aria-checked', value.toString() ); } return this; }; /** * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags}, * and {@link OO.ui.mixin.LabelElement labels}. Please see * the [OOjs UI documentation][1] on MediaWiki for more information. * * @example * // Toggle buttons in the 'off' and 'on' state. * var toggleButton1 = new OO.ui.ToggleButtonWidget( { * label: 'Toggle Button off' * } ); * var toggleButton2 = new OO.ui.ToggleButtonWidget( { * label: 'Toggle Button on', * value: true * } ); * // Append the buttons to the DOM. * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons * * @class * @extends OO.ui.ToggleWidget * @mixins OO.ui.mixin.ButtonElement * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [value=false] The toggle button’s initial on/off * state. By default, the button is in the 'off' state. */ OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ToggleButtonWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { active: this.active } ) ); OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) ); // Events this.connect( this, { click: 'onAction' } ); // Initialization this.$button.append( this.$icon, this.$label, this.$indicator ); this.$element .addClass( 'oo-ui-toggleButtonWidget' ) .append( this.$button ); }; /* Setup */ OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget ); OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement ); OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * Handle the button action being triggered. * * @private */ OO.ui.ToggleButtonWidget.prototype.onAction = function () { this.setValue( !this.value ); }; /** * @inheritdoc */ OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) { value = !!value; if ( value !== this.value ) { // Might be called from parent constructor before ButtonElement constructor if ( this.$button ) { this.$button.attr( 'aria-pressed', value.toString() ); } this.setActive( value ); } // Parent method OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value ); return this; }; /** * @inheritdoc */ OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) { if ( this.$button ) { this.$button.removeAttr( 'aria-pressed' ); } OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button ); this.$button.attr( 'aria-pressed', this.value.toString() ); }; /** * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented * visually by a slider in the leftmost position. * * @example * // Toggle switches in the 'off' and 'on' position. * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget(); * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( { * value: true * } ); * * // Create a FieldsetLayout to layout and label switches * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Toggle switches' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ), * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } ) * ] ); * $( 'body' ).append( fieldset.$element ); * * @class * @extends OO.ui.ToggleWidget * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [value=false] The toggle switch’s initial on/off state. * By default, the toggle switch is in the 'off' position. */ OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) { // Parent constructor OO.ui.ToggleSwitchWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.TabIndexedElement.call( this, config ); // Properties this.dragging = false; this.dragStart = null; this.sliding = false; this.$glow = $( '<span>' ); this.$grip = $( '<span>' ); // Events this.$element.on( { click: this.onClick.bind( this ), keypress: this.onKeyPress.bind( this ) } ); // Initialization this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' ); this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' ); this.$element .addClass( 'oo-ui-toggleSwitchWidget' ) .attr( 'role', 'checkbox' ) .append( this.$glow, this.$grip ); }; /* Setup */ OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget ); OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * Handle mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) { this.setValue( !this.value ); } return false; }; /** * Handle key press events. * * @private * @param {jQuery.Event} e Key press event */ OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.setValue( !this.value ); return false; } }; /** * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}. * Controls include moving items up and down, removing items, and adding different kinds of items. * * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.** * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupElement * @mixins OO.ui.mixin.IconElement * * @constructor * @param {OO.ui.OutlineSelectWidget} outline Outline to control * @param {Object} [config] Configuration options * @cfg {Object} [abilities] List of abilties * @cfg {boolean} [abilities.move=true] Allow moving movable items * @cfg {boolean} [abilities.remove=true] Allow removing removable items */ OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( outline ) && config === undefined ) { config = outline; outline = config.outline; } // Configuration initialization config = $.extend( { icon: 'add' }, config ); // Parent constructor OO.ui.OutlineControlsWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, config ); OO.ui.mixin.IconElement.call( this, config ); // Properties this.outline = outline; this.$movers = $( '<div>' ); this.upButton = new OO.ui.ButtonWidget( { framed: false, icon: 'collapse', title: OO.ui.msg( 'ooui-outline-control-move-up' ) } ); this.downButton = new OO.ui.ButtonWidget( { framed: false, icon: 'expand', title: OO.ui.msg( 'ooui-outline-control-move-down' ) } ); this.removeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'remove', title: OO.ui.msg( 'ooui-outline-control-remove' ) } ); this.abilities = { move: true, remove: true }; // Events outline.connect( this, { select: 'onOutlineChange', add: 'onOutlineChange', remove: 'onOutlineChange' } ); this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } ); this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } ); this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } ); // Initialization this.$element.addClass( 'oo-ui-outlineControlsWidget' ); this.$group.addClass( 'oo-ui-outlineControlsWidget-items' ); this.$movers .addClass( 'oo-ui-outlineControlsWidget-movers' ) .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element ); this.$element.append( this.$icon, this.$group, this.$movers ); this.setAbilities( config.abilities || {} ); }; /* Setup */ OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement ); OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement ); /* Events */ /** * @event move * @param {number} places Number of places to move */ /** * @event remove */ /* Methods */ /** * Set abilities. * * @param {Object} abilities List of abilties * @param {boolean} [abilities.move] Allow moving movable items * @param {boolean} [abilities.remove] Allow removing removable items */ OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) { var ability; for ( ability in this.abilities ) { if ( abilities[ ability ] !== undefined ) { this.abilities[ ability ] = !!abilities[ ability ]; } } this.onOutlineChange(); }; /** * Handle outline change events. * * @private */ OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () { var i, len, firstMovable, lastMovable, items = this.outline.getItems(), selectedItem = this.outline.getSelectedItem(), movable = this.abilities.move && selectedItem && selectedItem.isMovable(), removable = this.abilities.remove && selectedItem && selectedItem.isRemovable(); if ( movable ) { i = -1; len = items.length; while ( ++i < len ) { if ( items[ i ].isMovable() ) { firstMovable = items[ i ]; break; } } i = len; while ( i-- ) { if ( items[ i ].isMovable() ) { lastMovable = items[ i ]; break; } } } this.upButton.setDisabled( !movable || selectedItem === firstMovable ); this.downButton.setDisabled( !movable || selectedItem === lastMovable ); this.removeButton.setDisabled( !removable ); }; /** * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}. * * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout} * for an example. * * @class * @extends OO.ui.DecoratedOptionWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {number} [level] Indentation level * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}. */ OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.OutlineOptionWidget.parent.call( this, config ); // Properties this.level = 0; this.movable = !!config.movable; this.removable = !!config.removable; // Initialization this.$element.addClass( 'oo-ui-outlineOptionWidget' ); this.setLevel( config.level ); }; /* Setup */ OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.OutlineOptionWidget.static.highlightable = true; /** * @static * @inheritdoc */ OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true; /** * @static * @inheritable * @property {string} */ OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-'; /** * @static * @inheritable * @property {number} */ OO.ui.OutlineOptionWidget.static.levels = 3; /* Methods */ /** * Check if item is movable. * * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}. * * @return {boolean} Item is movable */ OO.ui.OutlineOptionWidget.prototype.isMovable = function () { return this.movable; }; /** * Check if item is removable. * * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}. * * @return {boolean} Item is removable */ OO.ui.OutlineOptionWidget.prototype.isRemovable = function () { return this.removable; }; /** * Get indentation level. * * @return {number} Indentation level */ OO.ui.OutlineOptionWidget.prototype.getLevel = function () { return this.level; }; /** * @inheritdoc */ OO.ui.OutlineOptionWidget.prototype.setPressed = function ( state ) { OO.ui.OutlineOptionWidget.parent.prototype.setPressed.call( this, state ); if ( this.pressed ) { this.setFlags( { progressive: true } ); } else if ( !this.selected ) { this.setFlags( { progressive: false } ); } return this; }; /** * Set movability. * * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}. * * @param {boolean} movable Item is movable * @chainable */ OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) { this.movable = !!movable; this.updateThemeClasses(); return this; }; /** * Set removability. * * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}. * * @param {boolean} removable Item is removable * @chainable */ OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) { this.removable = !!removable; this.updateThemeClasses(); return this; }; /** * @inheritdoc */ OO.ui.OutlineOptionWidget.prototype.setSelected = function ( state ) { OO.ui.OutlineOptionWidget.parent.prototype.setSelected.call( this, state ); if ( this.selected ) { this.setFlags( { progressive: true } ); } else { this.setFlags( { progressive: false } ); } return this; }; /** * Set indentation level. * * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel] * @chainable */ OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) { var levels = this.constructor.static.levels, levelClass = this.constructor.static.levelClass, i = levels; this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0; while ( i-- ) { if ( this.level === i ) { this.$element.addClass( levelClass + i ); } else { this.$element.removeClass( levelClass + i ); } } this.updateThemeClasses(); return this; }; /** * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options} * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget. * * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.** * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) { // Parent constructor OO.ui.OutlineSelectWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.TabIndexedElement.call( this, config ); // Events this.$element.on( { focus: this.bindKeyDownListener.bind( this ), blur: this.unbindKeyDownListener.bind( this ) } ); // Initialization this.$element.addClass( 'oo-ui-outlineSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement ); /** * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that * can be selected and configured with data. The class is * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the * [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options * * @class * @extends OO.ui.OptionWidget * @mixins OO.ui.mixin.ButtonElement * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ButtonOptionWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ButtonElement.call( this, config ); OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) ); // Initialization this.$element.addClass( 'oo-ui-buttonOptionWidget' ); this.$button.append( this.$icon, this.$label, this.$indicator ); this.$element.append( this.$button ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget ); OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement ); OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement ); /* Static Properties */ /** * Allow button mouse down events to pass through so they can be handled by the parent select widget * * @static * @inheritdoc */ OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false; /** * @static * @inheritdoc */ OO.ui.ButtonOptionWidget.static.highlightable = false; /* Methods */ /** * @inheritdoc */ OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) { OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state ); if ( this.constructor.static.selectable ) { this.setActive( state ); } return this; }; /** * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains * button options and is used together with * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for * highlighting, choosing, and selecting mutually exclusive options. Please see * the [OOjs UI documentation on MediaWiki] [1] for more information. * * @example * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets * var option1 = new OO.ui.ButtonOptionWidget( { * data: 1, * label: 'Option 1', * title: 'Button option 1' * } ); * * var option2 = new OO.ui.ButtonOptionWidget( { * data: 2, * label: 'Option 2', * title: 'Button option 2' * } ); * * var option3 = new OO.ui.ButtonOptionWidget( { * data: 3, * label: 'Option 3', * title: 'Button option 3' * } ); * * var buttonSelect=new OO.ui.ButtonSelectWidget( { * items: [ option1, option2, option3 ] * } ); * $( 'body' ).append( buttonSelect.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) { // Parent constructor OO.ui.ButtonSelectWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.TabIndexedElement.call( this, config ); // Events this.$element.on( { focus: this.bindKeyDownListener.bind( this ), blur: this.unbindKeyDownListener.bind( this ) } ); // Initialization this.$element.addClass( 'oo-ui-buttonSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement ); /** * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}. * * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout} * for an example. * * @class * @extends OO.ui.OptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.TabOptionWidget.parent.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-tabOptionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.TabOptionWidget.static.highlightable = false; /** * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options} * * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.** * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) { // Parent constructor OO.ui.TabSelectWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.TabIndexedElement.call( this, config ); // Events this.$element.on( { focus: this.bindKeyDownListener.bind( this ), blur: this.unbindKeyDownListener.bind( this ) } ); // Initialization this.$element.addClass( 'oo-ui-tabSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement ); /** * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiselectWidget * CapsuleMultiselectWidget} to display the selected items. * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.ItemWidget * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.CapsuleItemWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ItemWidget.call( this ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.TabIndexedElement.call( this, config ); // Events this.closeButton = new OO.ui.ButtonWidget( { framed: false, indicator: 'clear', tabIndex: -1 } ).on( 'click', this.onCloseClick.bind( this ) ); this.on( 'disable', function ( disabled ) { this.closeButton.setDisabled( disabled ); }.bind( this ) ); // Initialization this.$element .on( { click: this.onClick.bind( this ), keydown: this.onKeyDown.bind( this ) } ) .addClass( 'oo-ui-capsuleItemWidget' ) .append( this.$label, this.closeButton.$element ); }; /* Setup */ OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget ); OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * Handle close icon clicks */ OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () { var element = this.getElementGroup(); if ( element && $.isFunction( element.removeItems ) ) { element.removeItems( [ this ] ); element.focus(); } }; /** * Handle click event for the entire capsule */ OO.ui.CapsuleItemWidget.prototype.onClick = function () { var element = this.getElementGroup(); if ( !this.isDisabled() && element && $.isFunction( element.editItem ) ) { element.editItem( this ); } }; /** * Handle keyDown event for the entire capsule * * @param {jQuery.Event} e Key down event */ OO.ui.CapsuleItemWidget.prototype.onKeyDown = function ( e ) { var element = this.getElementGroup(); if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) { element.removeItems( [ this ] ); element.focus(); return false; } else if ( e.keyCode === OO.ui.Keys.ENTER ) { element.editItem( this ); return false; } else if ( e.keyCode === OO.ui.Keys.LEFT ) { element.getPreviousItem( this ).focus(); } else if ( e.keyCode === OO.ui.Keys.RIGHT ) { element.getNextItem( this ).focus(); } }; /** * Focuses the capsule */ OO.ui.CapsuleItemWidget.prototype.focus = function () { this.$element.focus(); }; /** * CapsuleMultiselectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget} * that allows for selecting multiple values. * * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example: A CapsuleMultiselectWidget. * var capsule = new OO.ui.CapsuleMultiselectWidget( { * label: 'CapsuleMultiselectWidget', * selected: [ 'Option 1', 'Option 3' ], * menu: { * items: [ * new OO.ui.MenuOptionWidget( { * data: 'Option 1', * label: 'Option One' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 2', * label: 'Option Two' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 3', * label: 'Option Three' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 4', * label: 'Option Four' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 5', * label: 'Option Five' * } ) * ] * } * } ); * $( 'body' ).append( capsule.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupElement * @mixins OO.ui.mixin.PopupElement * @mixins OO.ui.mixin.TabIndexedElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.IconElement * @uses OO.ui.CapsuleItemWidget * @uses OO.ui.FloatingMenuSelectWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [placeholder] Placeholder text * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu. * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added. * @cfg {Object} [menu] (required) Configuration options to pass to the * {@link OO.ui.MenuSelectWidget menu select widget}. * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}. * If specified, this popup will be shown instead of the menu (but the menu * will still be used for item labels and allowArbitrary=false). The widgets * in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary. * @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer. * This configuration is useful in cases where the expanded menu is larger than * its containing `<div>`. The specified overlay layer is usually on top of * the containing `<div>` and has a larger area. By default, the menu uses * relative positioning. */ OO.ui.CapsuleMultiselectWidget = function OoUiCapsuleMultiselectWidget( config ) { var $tabFocus; // Parent constructor OO.ui.CapsuleMultiselectWidget.parent.call( this, config ); // Configuration initialization config = $.extend( { allowArbitrary: false, allowDuplicates: false, $overlay: this.$element }, config ); // Properties (must be set before mixin constructor calls) this.$handle = $( '<div>' ); this.$input = config.popup ? null : $( '<input>' ); if ( config.placeholder !== undefined && config.placeholder !== '' ) { this.$input.attr( 'placeholder', config.placeholder ); } // Mixin constructors OO.ui.mixin.GroupElement.call( this, config ); if ( config.popup ) { config.popup = $.extend( {}, config.popup, { align: 'forwards', anchor: false } ); OO.ui.mixin.PopupElement.call( this, $.extend( true, {}, config, { popup: { $floatableContainer: this.$element } } ) ); $tabFocus = $( '<span>' ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) ); } else { this.popup = null; $tabFocus = null; OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) ); } OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.IconElement.call( this, config ); // Properties this.$content = $( '<div>' ); this.allowArbitrary = config.allowArbitrary; this.allowDuplicates = config.allowDuplicates; this.$overlay = config.$overlay; this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( { widget: this, $input: this.$input, $container: this.$element, filterFromInput: true, disabled: this.isDisabled() }, config.menu ) ); // Events if ( this.popup ) { $tabFocus.on( { focus: this.focus.bind( this ) } ); this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) ); if ( this.popup.$autoCloseIgnore ) { this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) ); } this.popup.connect( this, { toggle: function ( visible ) { $tabFocus.toggle( !visible ); } } ); } else { this.$input.on( { focus: this.onInputFocus.bind( this ), blur: this.onInputBlur.bind( this ), 'propertychange change click mouseup keydown keyup input cut paste select focus': OO.ui.debounce( this.updateInputSize.bind( this ) ), keydown: this.onKeyDown.bind( this ), keypress: this.onKeyPress.bind( this ) } ); } this.menu.connect( this, { choose: 'onMenuChoose', toggle: 'onMenuToggle', add: 'onMenuItemsChange', remove: 'onMenuItemsChange' } ); this.$handle.on( { mousedown: this.onMouseDown.bind( this ) } ); // Initialization if ( this.$input ) { this.$input.prop( 'disabled', this.isDisabled() ); this.$input.attr( { role: 'combobox', 'aria-autocomplete': 'list' } ); } if ( config.data ) { this.setItemsFromData( config.data ); } this.$content.addClass( 'oo-ui-capsuleMultiselectWidget-content' ) .append( this.$group ); this.$group.addClass( 'oo-ui-capsuleMultiselectWidget-group' ); this.$handle.addClass( 'oo-ui-capsuleMultiselectWidget-handle' ) .append( this.$indicator, this.$icon, this.$content ); this.$element.addClass( 'oo-ui-capsuleMultiselectWidget' ) .append( this.$handle ); if ( this.popup ) { this.popup.$element.addClass( 'oo-ui-capsuleMultiselectWidget-popup' ); this.$content.append( $tabFocus ); this.$overlay.append( this.popup.$element ); } else { this.$content.append( this.$input ); this.$overlay.append( this.menu.$element ); } if ( $tabFocus ) { $tabFocus.addClass( 'oo-ui-capsuleMultiselectWidget-focusTrap' ); } // Input size needs to be calculated after everything else is rendered setTimeout( function () { if ( this.$input ) { this.updateInputSize(); } }.bind( this ) ); this.onMenuItemsChange(); }; /* Setup */ OO.inheritClass( OO.ui.CapsuleMultiselectWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.GroupElement ); OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.PopupElement ); OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.TabIndexedElement ); OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IconElement ); /* Static Properties */ OO.ui.CapsuleMultiselectWidget.static.supportsSimpleLabel = true; /* Events */ /** * @event change * * A change event is emitted when the set of selected items changes. * * @param {Mixed[]} datas Data of the now-selected items */ /** * @event resize * * A resize event is emitted when the widget's dimensions change to accomodate newly added items or * current user input. */ /* Methods */ /** * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data. * May return `null` if the given label and data are not valid. * * @protected * @param {Mixed} data Custom data of any type. * @param {string} label The label text. * @return {OO.ui.CapsuleItemWidget|null} */ OO.ui.CapsuleMultiselectWidget.prototype.createItemWidget = function ( data, label ) { if ( label === '' ) { return null; } return new OO.ui.CapsuleItemWidget( { data: data, label: label } ); }; /** * Get the widget's input's id, or generate one, if it has an input. * * @return {string} */ OO.ui.CapsuleMultiselectWidget.prototype.getInputId = function () { var id; if ( !this.$input ) { return false; } id = this.$input.attr( 'id' ); if ( id === undefined ) { id = OO.ui.generateElementId(); this.$input.attr( 'id', id ); } return id; }; /** * Get the data of the items in the capsule * * @return {Mixed[]} */ OO.ui.CapsuleMultiselectWidget.prototype.getItemsData = function () { return this.getItems().map( function ( item ) { return item.data; } ); }; /** * Set the items in the capsule by providing data * * @chainable * @param {Mixed[]} datas * @return {OO.ui.CapsuleMultiselectWidget} */ OO.ui.CapsuleMultiselectWidget.prototype.setItemsFromData = function ( datas ) { var widget = this, menu = this.menu, items = this.getItems(); $.each( datas, function ( i, data ) { var j, label, item = menu.getItemFromData( data ); if ( item ) { label = item.label; } else if ( widget.allowArbitrary ) { label = String( data ); } else { return; } item = null; for ( j = 0; j < items.length; j++ ) { if ( items[ j ].data === data && items[ j ].label === label ) { item = items[ j ]; items.splice( j, 1 ); break; } } if ( !item ) { item = widget.createItemWidget( data, label ); } if ( item ) { widget.addItems( [ item ], i ); } } ); if ( items.length ) { widget.removeItems( items ); } return this; }; /** * Add items to the capsule by providing their data * * @chainable * @param {Mixed[]} datas * @return {OO.ui.CapsuleMultiselectWidget} */ OO.ui.CapsuleMultiselectWidget.prototype.addItemsFromData = function ( datas ) { var widget = this, menu = this.menu, items = []; $.each( datas, function ( i, data ) { var item; if ( !widget.getItemFromData( data ) || widget.allowDuplicates ) { item = menu.getItemFromData( data ); if ( item ) { item = widget.createItemWidget( data, item.label ); } else if ( widget.allowArbitrary ) { item = widget.createItemWidget( data, String( data ) ); } if ( item ) { items.push( item ); } } } ); if ( items.length ) { this.addItems( items ); } return this; }; /** * Add items to the capsule by providing a label * * @param {string} label * @return {boolean} Whether the item was added or not */ OO.ui.CapsuleMultiselectWidget.prototype.addItemFromLabel = function ( label ) { var item, items; item = this.menu.getItemFromLabel( label, true ); if ( item ) { this.addItemsFromData( [ item.data ] ); return true; } else if ( this.allowArbitrary ) { items = this.getItems(); this.addItemsFromData( [ label ] ); return !OO.compare( this.getItems(), items ); } return false; }; /** * Remove items by data * * @chainable * @param {Mixed[]} datas * @return {OO.ui.CapsuleMultiselectWidget} */ OO.ui.CapsuleMultiselectWidget.prototype.removeItemsFromData = function ( datas ) { var widget = this, items = []; $.each( datas, function ( i, data ) { var item = widget.getItemFromData( data ); if ( item ) { items.push( item ); } } ); if ( items.length ) { this.removeItems( items ); } return this; }; /** * @inheritdoc */ OO.ui.CapsuleMultiselectWidget.prototype.addItems = function ( items ) { var same, i, l, oldItems = this.items.slice(); OO.ui.mixin.GroupElement.prototype.addItems.call( this, items ); if ( this.items.length !== oldItems.length ) { same = false; } else { same = true; for ( i = 0, l = oldItems.length; same && i < l; i++ ) { same = same && this.items[ i ] === oldItems[ i ]; } } if ( !same ) { this.emit( 'change', this.getItemsData() ); this.updateIfHeightChanged(); } return this; }; /** * Removes the item from the list and copies its label to `this.$input`. * * @param {Object} item */ OO.ui.CapsuleMultiselectWidget.prototype.editItem = function ( item ) { this.addItemFromLabel( this.$input.val() ); this.clearInput(); this.$input.val( item.label ); this.updateInputSize(); this.focus(); this.menu.updateItemVisibility(); // Hack, we shouldn't be calling this method directly this.removeItems( [ item ] ); }; /** * @inheritdoc */ OO.ui.CapsuleMultiselectWidget.prototype.removeItems = function ( items ) { var same, i, l, oldItems = this.items.slice(); OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items ); if ( this.items.length !== oldItems.length ) { same = false; } else { same = true; for ( i = 0, l = oldItems.length; same && i < l; i++ ) { same = same && this.items[ i ] === oldItems[ i ]; } } if ( !same ) { this.emit( 'change', this.getItemsData() ); this.updateIfHeightChanged(); } return this; }; /** * @inheritdoc */ OO.ui.CapsuleMultiselectWidget.prototype.clearItems = function () { if ( this.items.length ) { OO.ui.mixin.GroupElement.prototype.clearItems.call( this ); this.emit( 'change', this.getItemsData() ); this.updateIfHeightChanged(); } return this; }; /** * Given an item, returns the item after it. If its the last item, * returns `this.$input`. If no item is passed, returns the very first * item. * * @param {OO.ui.CapsuleItemWidget} [item] * @return {OO.ui.CapsuleItemWidget|jQuery|boolean} */ OO.ui.CapsuleMultiselectWidget.prototype.getNextItem = function ( item ) { var itemIndex; if ( item === undefined ) { return this.items[ 0 ]; } itemIndex = this.items.indexOf( item ); if ( itemIndex < 0 ) { // Item not in list return false; } else if ( itemIndex === this.items.length - 1 ) { // Last item return this.$input; } else { return this.items[ itemIndex + 1 ]; } }; /** * Given an item, returns the item before it. If its the first item, * returns `this.$input`. If no item is passed, returns the very last * item. * * @param {OO.ui.CapsuleItemWidget} [item] * @return {OO.ui.CapsuleItemWidget|jQuery|boolean} */ OO.ui.CapsuleMultiselectWidget.prototype.getPreviousItem = function ( item ) { var itemIndex; if ( item === undefined ) { return this.items[ this.items.length - 1 ]; } itemIndex = this.items.indexOf( item ); if ( itemIndex < 0 ) { // Item not in list return false; } else if ( itemIndex === 0 ) { // First item return this.$input; } else { return this.items[ itemIndex - 1 ]; } }; /** * Get the capsule widget's menu. * * @return {OO.ui.MenuSelectWidget} Menu widget */ OO.ui.CapsuleMultiselectWidget.prototype.getMenu = function () { return this.menu; }; /** * Handle focus events * * @private * @param {jQuery.Event} event */ OO.ui.CapsuleMultiselectWidget.prototype.onInputFocus = function () { if ( !this.isDisabled() ) { this.menu.toggle( true ); } }; /** * Handle blur events * * @private * @param {jQuery.Event} event */ OO.ui.CapsuleMultiselectWidget.prototype.onInputBlur = function () { this.addItemFromLabel( this.$input.val() ); this.clearInput(); }; /** * Handles popup focus out events. * * @private * @param {jQuery.Event} e Focus out event */ OO.ui.CapsuleMultiselectWidget.prototype.onPopupFocusOut = function () { var widget = this.popup; setTimeout( function () { if ( widget.isVisible() && !OO.ui.contains( widget.$element.add( widget.$autoCloseIgnore ).get(), document.activeElement, true ) ) { widget.toggle( false ); } } ); }; /** * Handle mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.CapsuleMultiselectWidget.prototype.onMouseDown = function ( e ) { if ( e.which === OO.ui.MouseButtons.LEFT ) { this.focus(); return false; } else { this.updateInputSize(); } }; /** * Handle key press events. * * @private * @param {jQuery.Event} e Key press event */ OO.ui.CapsuleMultiselectWidget.prototype.onKeyPress = function ( e ) { if ( !this.isDisabled() ) { if ( e.which === OO.ui.Keys.ESCAPE ) { this.clearInput(); return false; } if ( !this.popup ) { this.menu.toggle( true ); if ( e.which === OO.ui.Keys.ENTER ) { if ( this.addItemFromLabel( this.$input.val() ) ) { this.clearInput(); } return false; } // Make sure the input gets resized. setTimeout( this.updateInputSize.bind( this ), 0 ); } } }; /** * Handle key down events. * * @private * @param {jQuery.Event} e Key down event */ OO.ui.CapsuleMultiselectWidget.prototype.onKeyDown = function ( e ) { if ( !this.isDisabled() && this.$input.val() === '' && this.items.length ) { // 'keypress' event is not triggered for Backspace if ( e.keyCode === OO.ui.Keys.BACKSPACE ) { if ( e.metaKey || e.ctrlKey ) { this.removeItems( this.items.slice( -1 ) ); } else { this.editItem( this.items[ this.items.length - 1 ] ); } return false; } else if ( e.keyCode === OO.ui.Keys.LEFT ) { this.getPreviousItem().focus(); } else if ( e.keyCode === OO.ui.Keys.RIGHT ) { this.getNextItem().focus(); } } }; /** * Update the dimensions of the text input field to encompass all available area. * * @private * @param {jQuery.Event} e Event of some sort */ OO.ui.CapsuleMultiselectWidget.prototype.updateInputSize = function () { var $lastItem, direction, contentWidth, currentWidth, bestWidth; if ( this.$input && !this.isDisabled() ) { this.$input.css( 'width', '1em' ); $lastItem = this.$group.children().last(); direction = OO.ui.Element.static.getDir( this.$handle ); // Get the width of the input with the placeholder text as // the value and save it so that we don't keep recalculating if ( this.contentWidthWithPlaceholder === undefined && this.$input.val() === '' && this.$input.attr( 'placeholder' ) !== undefined ) { this.$input.val( this.$input.attr( 'placeholder' ) ); this.contentWidthWithPlaceholder = this.$input[ 0 ].scrollWidth; this.$input.val( '' ); } // Always keep the input wide enough for the placeholder text contentWidth = Math.max( this.$input[ 0 ].scrollWidth, // undefined arguments in Math.max lead to NaN ( this.contentWidthWithPlaceholder === undefined ) ? 0 : this.contentWidthWithPlaceholder ); currentWidth = this.$input.width(); if ( contentWidth < currentWidth ) { // All is fine, don't perform expensive calculations return; } if ( $lastItem.length === 0 ) { bestWidth = this.$content.innerWidth(); } else { bestWidth = direction === 'ltr' ? this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() : $lastItem.position().left; } // Some safety margin for sanity, because I *really* don't feel like finding out where the few // pixels this is off by are coming from. bestWidth -= 10; if ( contentWidth > bestWidth ) { // This will result in the input getting shifted to the next line bestWidth = this.$content.innerWidth() - 10; } this.$input.width( Math.floor( bestWidth ) ); this.updateIfHeightChanged(); } }; /** * Determine if widget height changed, and if so, update menu position and emit 'resize' event. * * @private */ OO.ui.CapsuleMultiselectWidget.prototype.updateIfHeightChanged = function () { var height = this.$element.height(); if ( height !== this.height ) { this.height = height; this.menu.position(); this.emit( 'resize' ); } }; /** * Handle menu choose events. * * @private * @param {OO.ui.OptionWidget} item Chosen item */ OO.ui.CapsuleMultiselectWidget.prototype.onMenuChoose = function ( item ) { if ( item && item.isVisible() ) { this.addItemsFromData( [ item.getData() ] ); this.clearInput(); } }; /** * Handle menu toggle events. * * @private * @param {boolean} isVisible Menu toggle event */ OO.ui.CapsuleMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) { this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-open', isVisible ); }; /** * Handle menu item change events. * * @private */ OO.ui.CapsuleMultiselectWidget.prototype.onMenuItemsChange = function () { this.setItemsFromData( this.getItemsData() ); this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu.isEmpty() ); }; /** * Clear the input field * * @private */ OO.ui.CapsuleMultiselectWidget.prototype.clearInput = function () { if ( this.$input ) { this.$input.val( '' ); this.updateInputSize(); } if ( this.popup ) { this.popup.toggle( false ); } this.menu.toggle( false ); this.menu.selectItem(); this.menu.highlightItem(); }; /** * @inheritdoc */ OO.ui.CapsuleMultiselectWidget.prototype.setDisabled = function ( disabled ) { var i, len; // Parent method OO.ui.CapsuleMultiselectWidget.parent.prototype.setDisabled.call( this, disabled ); if ( this.$input ) { this.$input.prop( 'disabled', this.isDisabled() ); } if ( this.menu ) { this.menu.setDisabled( this.isDisabled() ); } if ( this.popup ) { this.popup.setDisabled( this.isDisabled() ); } if ( this.items ) { for ( i = 0, len = this.items.length; i < len; i++ ) { this.items[ i ].updateDisabled(); } } return this; }; /** * Focus the widget * * @chainable * @return {OO.ui.CapsuleMultiselectWidget} */ OO.ui.CapsuleMultiselectWidget.prototype.focus = function () { if ( !this.isDisabled() ) { if ( this.popup ) { this.popup.setSize( this.$handle.outerWidth() ); this.popup.toggle( true ); OO.ui.findFocusable( this.popup.$element ).focus(); } else { this.updateInputSize(); this.menu.toggle( true ); this.$input.focus(); } } return this; }; /** * The old name for the CapsuleMultiselectWidget widget, provided for backwards-compatibility. * * @class * @extends OO.ui.CapsuleMultiselectWidget * * @constructor * @deprecated since 0.17.3; use OO.ui.CapsuleMultiselectWidget instead */ OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget() { OO.ui.warnDeprecation( 'CapsuleMultiSelectWidget is deprecated. Use the CapsuleMultiselectWidget instead.' ); // Parent constructor OO.ui.CapsuleMultiSelectWidget.parent.apply( this, arguments ); }; OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.CapsuleMultiselectWidget ); /** * SelectFileWidgets allow for selecting files, using the HTML5 File API. These * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link * OO.ui.mixin.IndicatorElement indicators}. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples. * * @example * // Example of a file select widget * var selectFile = new OO.ui.SelectFileWidget(); * $( 'body' ).append( selectFile.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.PendingElement * @mixins OO.ui.mixin.LabelElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types. * @cfg {string} [placeholder] Text to display when no file is selected. * @cfg {string} [notsupported] Text to display when file support is missing in the browser. * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop. * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true. * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a * preview (for performance) */ OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) { var dragHandler; // Configuration initialization config = $.extend( { accept: null, placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ), notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ), droppable: true, showDropTarget: false, thumbnailSizeLimit: 20 }, config ); // Parent constructor OO.ui.SelectFileWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) ); OO.ui.mixin.LabelElement.call( this, config ); // Properties this.$info = $( '<span>' ); this.showDropTarget = config.showDropTarget; this.thumbnailSizeLimit = config.thumbnailSizeLimit; this.isSupported = this.constructor.static.isSupported(); this.currentFile = null; if ( Array.isArray( config.accept ) ) { this.accept = config.accept; } else { this.accept = null; } this.placeholder = config.placeholder; this.notsupported = config.notsupported; this.onFileSelectedHandler = this.onFileSelected.bind( this ); this.selectButton = new OO.ui.ButtonWidget( { classes: [ 'oo-ui-selectFileWidget-selectButton' ], label: OO.ui.msg( 'ooui-selectfile-button-select' ), disabled: this.disabled || !this.isSupported } ); this.clearButton = new OO.ui.ButtonWidget( { classes: [ 'oo-ui-selectFileWidget-clearButton' ], framed: false, icon: 'close', disabled: this.disabled } ); // Events this.selectButton.$button.on( { keypress: this.onKeyPress.bind( this ) } ); this.clearButton.connect( this, { click: 'onClearClick' } ); if ( config.droppable ) { dragHandler = this.onDragEnterOrOver.bind( this ); this.$element.on( { dragenter: dragHandler, dragover: dragHandler, dragleave: this.onDragLeave.bind( this ), drop: this.onDrop.bind( this ) } ); } // Initialization this.addInput(); this.$label.addClass( 'oo-ui-selectFileWidget-label' ); this.$info .addClass( 'oo-ui-selectFileWidget-info' ) .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator ); if ( config.droppable && config.showDropTarget ) { this.selectButton.setIcon( 'upload' ); this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' ); this.setPendingElement( this.$thumbnail ); this.$element .addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' ) .on( { click: this.onDropTargetClick.bind( this ) } ) .append( this.$thumbnail, this.$info, this.selectButton.$element, $( '<span>' ) .addClass( 'oo-ui-selectFileWidget-dropLabel' ) .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) ) ); } else { this.$element .addClass( 'oo-ui-selectFileWidget' ) .append( this.$info, this.selectButton.$element ); } this.updateUI(); }; /* Setup */ OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement ); OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement ); /* Static Properties */ /** * Check if this widget is supported * * @static * @return {boolean} */ OO.ui.SelectFileWidget.static.isSupported = function () { var $input; if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) { $input = $( '<input>' ).attr( 'type', 'file' ); OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined; } return OO.ui.SelectFileWidget.static.isSupportedCache; }; OO.ui.SelectFileWidget.static.isSupportedCache = null; /* Events */ /** * @event change * * A change event is emitted when the on/off state of the toggle changes. * * @param {File|null} value New value */ /* Methods */ /** * Get the current value of the field * * @return {File|null} */ OO.ui.SelectFileWidget.prototype.getValue = function () { return this.currentFile; }; /** * Set the current value of the field * * @param {File|null} file File to select */ OO.ui.SelectFileWidget.prototype.setValue = function ( file ) { if ( this.currentFile !== file ) { this.currentFile = file; this.updateUI(); this.emit( 'change', this.currentFile ); } }; /** * Focus the widget. * * Focusses the select file button. * * @chainable */ OO.ui.SelectFileWidget.prototype.focus = function () { this.selectButton.$button[ 0 ].focus(); return this; }; /** * Update the user interface when a file is selected or unselected * * @protected */ OO.ui.SelectFileWidget.prototype.updateUI = function () { var $label; if ( !this.isSupported ) { this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' ); this.$element.removeClass( 'oo-ui-selectFileWidget-empty' ); this.setLabel( this.notsupported ); } else { this.$element.addClass( 'oo-ui-selectFileWidget-supported' ); if ( this.currentFile ) { this.$element.removeClass( 'oo-ui-selectFileWidget-empty' ); $label = $( [] ); $label = $label.add( $( '<span>' ) .addClass( 'oo-ui-selectFileWidget-fileName' ) .text( this.currentFile.name ) ); this.setLabel( $label ); if ( this.showDropTarget ) { this.pushPending(); this.loadAndGetImageUrl().done( function ( url ) { this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' ); }.bind( this ) ).fail( function () { this.$thumbnail.append( new OO.ui.IconWidget( { icon: 'attachment', classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ] } ).$element ); }.bind( this ) ).always( function () { this.popPending(); }.bind( this ) ); this.$element.off( 'click' ); } } else { if ( this.showDropTarget ) { this.$element.off( 'click' ); this.$element.on( { click: this.onDropTargetClick.bind( this ) } ); this.$thumbnail .empty() .css( 'background-image', '' ); } this.$element.addClass( 'oo-ui-selectFileWidget-empty' ); this.setLabel( this.placeholder ); } } }; /** * If the selected file is an image, get its URL and load it. * * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded */ OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () { var deferred = $.Deferred(), file = this.currentFile, reader = new FileReader(); if ( file && ( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 && file.size < this.thumbnailSizeLimit * 1024 * 1024 ) { reader.onload = function ( event ) { var img = document.createElement( 'img' ); img.addEventListener( 'load', function () { if ( img.naturalWidth === 0 || img.naturalHeight === 0 || img.complete === false ) { deferred.reject(); } else { deferred.resolve( event.target.result ); } } ); img.src = event.target.result; }; reader.readAsDataURL( file ); } else { deferred.reject(); } return deferred.promise(); }; /** * Add the input to the widget * * @private */ OO.ui.SelectFileWidget.prototype.addInput = function () { if ( this.$input ) { this.$input.remove(); } if ( !this.isSupported ) { this.$input = null; return; } this.$input = $( '<input>' ).attr( 'type', 'file' ); this.$input.on( 'change', this.onFileSelectedHandler ); this.$input.on( 'click', function ( e ) { // Prevents dropTarget to get clicked which calls // a click on this input e.stopPropagation(); } ); this.$input.attr( { tabindex: -1 } ); if ( this.accept ) { this.$input.attr( 'accept', this.accept.join( ', ' ) ); } this.selectButton.$button.append( this.$input ); }; /** * Determine if we should accept this file * * @private * @param {string} mimeType File MIME type * @return {boolean} */ OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) { var i, mimeTest; if ( !this.accept || !mimeType ) { return true; } for ( i = 0; i < this.accept.length; i++ ) { mimeTest = this.accept[ i ]; if ( mimeTest === mimeType ) { return true; } else if ( mimeTest.substr( -2 ) === '/*' ) { mimeTest = mimeTest.substr( 0, mimeTest.length - 1 ); if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) { return true; } } } return false; }; /** * Handle file selection from the input * * @private * @param {jQuery.Event} e */ OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) { var file = OO.getProp( e.target, 'files', 0 ) || null; if ( file && !this.isAllowedType( file.type ) ) { file = null; } this.setValue( file ); this.addInput(); }; /** * Handle clear button click events. * * @private */ OO.ui.SelectFileWidget.prototype.onClearClick = function () { this.setValue( null ); return false; }; /** * Handle key press events. * * @private * @param {jQuery.Event} e Key press event */ OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) { if ( this.isSupported && !this.isDisabled() && this.$input && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.$input.click(); return false; } }; /** * Handle drop target click events. * * @private * @param {jQuery.Event} e Key press event */ OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () { if ( this.isSupported && !this.isDisabled() && this.$input ) { this.$input.click(); return false; } }; /** * Handle drag enter and over events * * @private * @param {jQuery.Event} e Drag event */ OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) { var itemOrFile, droppableFile = false, dt = e.originalEvent.dataTransfer; e.preventDefault(); e.stopPropagation(); if ( this.isDisabled() || !this.isSupported ) { this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' ); dt.dropEffect = 'none'; return false; } // DataTransferItem and File both have a type property, but in Chrome files // have no information at this point. itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 ); if ( itemOrFile ) { if ( this.isAllowedType( itemOrFile.type ) ) { droppableFile = true; } // dt.types is Array-like, but not an Array } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) { // File information is not available at this point for security so just assume // it is acceptable for now. // https://bugzilla.mozilla.org/show_bug.cgi?id=640534 droppableFile = true; } this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile ); if ( !droppableFile ) { dt.dropEffect = 'none'; } return false; }; /** * Handle drag leave events * * @private * @param {jQuery.Event} e Drag event */ OO.ui.SelectFileWidget.prototype.onDragLeave = function () { this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' ); }; /** * Handle drop events * * @private * @param {jQuery.Event} e Drop event */ OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) { var file = null, dt = e.originalEvent.dataTransfer; e.preventDefault(); e.stopPropagation(); this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' ); if ( this.isDisabled() || !this.isSupported ) { return false; } file = OO.getProp( dt, 'files', 0 ); if ( file && !this.isAllowedType( file.type ) ) { file = null; } if ( file ) { this.setValue( file ); } return false; }; /** * @inheritdoc */ OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) { OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled ); if ( this.selectButton ) { this.selectButton.setDisabled( disabled ); } if ( this.clearButton ) { this.clearButton.setDisabled( disabled ); } return this; }; /** * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query, * and a menu of search results, which is displayed beneath the query * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user. * Users can choose an item from the menu or type a query into the text field to search for a matching result item. * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window. * * Each time the query is changed, the search result menu is cleared and repopulated. Please see * the [OOjs UI demos][1] for an example. * * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr * * @class * @extends OO.ui.Widget * * @constructor * @param {Object} [config] Configuration options * @cfg {string|jQuery} [placeholder] Placeholder text for query input * @cfg {string} [value] Initial query value */ OO.ui.SearchWidget = function OoUiSearchWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.SearchWidget.parent.call( this, config ); // Properties this.query = new OO.ui.TextInputWidget( { icon: 'search', placeholder: config.placeholder, value: config.value } ); this.results = new OO.ui.SelectWidget(); this.$query = $( '<div>' ); this.$results = $( '<div>' ); // Events this.query.connect( this, { change: 'onQueryChange', enter: 'onQueryEnter' } ); this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) ); // Initialization this.$query .addClass( 'oo-ui-searchWidget-query' ) .append( this.query.$element ); this.$results .addClass( 'oo-ui-searchWidget-results' ) .append( this.results.$element ); this.$element .addClass( 'oo-ui-searchWidget' ) .append( this.$results, this.$query ); }; /* Setup */ OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget ); /* Methods */ /** * Handle query key down events. * * @private * @param {jQuery.Event} e Key down event */ OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) { var highlightedItem, nextItem, dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 ); if ( dir ) { highlightedItem = this.results.getHighlightedItem(); if ( !highlightedItem ) { highlightedItem = this.results.getSelectedItem(); } nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir ); this.results.highlightItem( nextItem ); nextItem.scrollElementIntoView(); } }; /** * Handle select widget select events. * * Clears existing results. Subclasses should repopulate items according to new query. * * @private * @param {string} value New value */ OO.ui.SearchWidget.prototype.onQueryChange = function () { // Reset this.results.clearItems(); }; /** * Handle select widget enter key events. * * Chooses highlighted item. * * @private * @param {string} value New value */ OO.ui.SearchWidget.prototype.onQueryEnter = function () { var highlightedItem = this.results.getHighlightedItem(); if ( highlightedItem ) { this.results.chooseItem( highlightedItem ); } }; /** * Get the query input. * * @return {OO.ui.TextInputWidget} Query input */ OO.ui.SearchWidget.prototype.getQuery = function () { return this.query; }; /** * Get the search results menu. * * @return {OO.ui.SelectWidget} Menu of search results */ OO.ui.SearchWidget.prototype.getResults = function () { return this.results; }; /** * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets} * (to adjust the value in increments) to allow the user to enter a number. * * @example * // Example: A NumberInputWidget. * var numberInput = new OO.ui.NumberInputWidget( { * label: 'NumberInputWidget', * input: { value: 5 }, * min: 1, * max: 10 * } ); * $( 'body' ).append( numberInput.$element ); * * @class * @extends OO.ui.Widget * * @constructor * @param {Object} [config] Configuration options * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}. * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}. * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}. * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values. * @cfg {number} [min=-Infinity] Minimum allowed value * @cfg {number} [max=Infinity] Maximum allowed value * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step. * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons. */ OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) { // Configuration initialization config = $.extend( { isInteger: false, min: -Infinity, max: Infinity, step: 1, pageStep: null, showButtons: true }, config ); // Parent constructor OO.ui.NumberInputWidget.parent.call( this, config ); // Properties this.input = new OO.ui.TextInputWidget( $.extend( { disabled: this.isDisabled(), type: 'number' }, config.input ) ); if ( config.showButtons ) { this.minusButton = new OO.ui.ButtonWidget( $.extend( { disabled: this.isDisabled(), tabIndex: -1, classes: [ 'oo-ui-numberInputWidget-minusButton' ], label: '−' }, config.minusButton ) ); this.plusButton = new OO.ui.ButtonWidget( $.extend( { disabled: this.isDisabled(), tabIndex: -1, classes: [ 'oo-ui-numberInputWidget-plusButton' ], label: '+' }, config.plusButton ) ); } // Events this.input.connect( this, { change: this.emit.bind( this, 'change' ), enter: this.emit.bind( this, 'enter' ) } ); this.input.$input.on( { keydown: this.onKeyDown.bind( this ), 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this ) } ); if ( config.showButtons ) { this.plusButton.connect( this, { click: [ 'onButtonClick', +1 ] } ); this.minusButton.connect( this, { click: [ 'onButtonClick', -1 ] } ); } // Initialization this.setIsInteger( !!config.isInteger ); this.setRange( config.min, config.max ); this.setStep( config.step, config.pageStep ); this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' ) .append( this.input.$element ); this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field ); if ( config.showButtons ) { this.$field .prepend( this.minusButton.$element ) .append( this.plusButton.$element ); this.$element.addClass( 'oo-ui-numberInputWidget-buttoned' ); } this.input.setValidation( this.validateNumber.bind( this ) ); }; /* Setup */ OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget ); /* Events */ /** * A `change` event is emitted when the value of the input changes. * * @event change */ /** * An `enter` event is emitted when the user presses 'enter' inside the text box. * * @event enter */ /* Methods */ /** * Set whether only integers are allowed * * @param {boolean} flag */ OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) { this.isInteger = !!flag; this.input.setValidityFlag(); }; /** * Get whether only integers are allowed * * @return {boolean} Flag value */ OO.ui.NumberInputWidget.prototype.getIsInteger = function () { return this.isInteger; }; /** * Set the range of allowed values * * @param {number} min Minimum allowed value * @param {number} max Maximum allowed value */ OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) { if ( min > max ) { throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' ); } this.min = min; this.max = max; this.input.setValidityFlag(); }; /** * Get the current range * * @return {number[]} Minimum and maximum values */ OO.ui.NumberInputWidget.prototype.getRange = function () { return [ this.min, this.max ]; }; /** * Set the stepping deltas * * @param {number} step Normal step * @param {number|null} pageStep Page step. If null, 10 * step will be used. */ OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) { if ( step <= 0 ) { throw new Error( 'Step value must be positive' ); } if ( pageStep === null ) { pageStep = step * 10; } else if ( pageStep <= 0 ) { throw new Error( 'Page step value must be positive' ); } this.step = step; this.pageStep = pageStep; }; /** * Get the current stepping values * * @return {number[]} Step and page step */ OO.ui.NumberInputWidget.prototype.getStep = function () { return [ this.step, this.pageStep ]; }; /** * Get the current value of the widget * * @return {string} */ OO.ui.NumberInputWidget.prototype.getValue = function () { return this.input.getValue(); }; /** * Get the current value of the widget as a number * * @return {number} May be NaN, or an invalid number */ OO.ui.NumberInputWidget.prototype.getNumericValue = function () { return +this.input.getValue(); }; /** * Set the value of the widget * * @param {string} value Invalid values are allowed */ OO.ui.NumberInputWidget.prototype.setValue = function ( value ) { this.input.setValue( value ); }; /** * Adjust the value of the widget * * @param {number} delta Adjustment amount */ OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) { var n, v = this.getNumericValue(); delta = +delta; if ( isNaN( delta ) || !isFinite( delta ) ) { throw new Error( 'Delta must be a finite number' ); } if ( isNaN( v ) ) { n = 0; } else { n = v + delta; n = Math.max( Math.min( n, this.max ), this.min ); if ( this.isInteger ) { n = Math.round( n ); } } if ( n !== v ) { this.setValue( n ); } }; /** * Validate input * * @private * @param {string} value Field value * @return {boolean} */ OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) { var n = +value; if ( isNaN( n ) || !isFinite( n ) ) { return false; } if ( this.isInteger && Math.floor( n ) !== n ) { return false; } if ( n < this.min || n > this.max ) { return false; } return true; }; /** * Handle mouse click events. * * @private * @param {number} dir +1 or -1 */ OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) { this.adjustValue( dir * this.step ); }; /** * Handle mouse wheel events. * * @private * @param {jQuery.Event} event */ OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) { var delta = 0; if ( !this.isDisabled() && this.input.$input.is( ':focus' ) ) { // Standard 'wheel' event if ( event.originalEvent.deltaMode !== undefined ) { this.sawWheelEvent = true; } if ( event.originalEvent.deltaY ) { delta = -event.originalEvent.deltaY; } else if ( event.originalEvent.deltaX ) { delta = event.originalEvent.deltaX; } // Non-standard events if ( !this.sawWheelEvent ) { if ( event.originalEvent.wheelDeltaX ) { delta = -event.originalEvent.wheelDeltaX; } else if ( event.originalEvent.wheelDeltaY ) { delta = event.originalEvent.wheelDeltaY; } else if ( event.originalEvent.wheelDelta ) { delta = event.originalEvent.wheelDelta; } else if ( event.originalEvent.detail ) { delta = -event.originalEvent.detail; } } if ( delta ) { delta = delta < 0 ? -1 : 1; this.adjustValue( delta * this.step ); } return false; } }; /** * Handle key down events. * * @private * @param {jQuery.Event} e Key down event */ OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) { if ( !this.isDisabled() ) { switch ( e.which ) { case OO.ui.Keys.UP: this.adjustValue( this.step ); return false; case OO.ui.Keys.DOWN: this.adjustValue( -this.step ); return false; case OO.ui.Keys.PAGEUP: this.adjustValue( this.pageStep ); return false; case OO.ui.Keys.PAGEDOWN: this.adjustValue( -this.pageStep ); return false; } } }; /** * @inheritdoc */ OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) { // Parent method OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled ); if ( this.input ) { this.input.setDisabled( this.isDisabled() ); } if ( this.minusButton ) { this.minusButton.setDisabled( this.isDisabled() ); } if ( this.plusButton ) { this.plusButton.setDisabled( this.isDisabled() ); } return this; }; }( OO ) ); //# sourceMappingURL=oojs-ui-widgets.js.map /*! * OOjs UI v0.19.3-pre (72b81a54a7) * https://www.mediawiki.org/wiki/OOjs_UI * * Copyright 2011–2017 OOjs UI Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2017-02-21T22:25:51Z */ ( function ( OO ) { 'use strict'; /** * Toolbars are complex interface components that permit users to easily access a variety * of {@link OO.ui.Tool tools} (e.g., formatting commands) and actions, which are additional commands that are * part of the toolbar, but not configured as tools. * * Individual tools are customized and then registered with a {@link OO.ui.ToolFactory tool factory}, which creates * the tools on demand. Each tool has a symbolic name (used when registering the tool), a title (e.g., ‘Insert * image’), and an icon. * * Individual tools are organized in {@link OO.ui.ToolGroup toolgroups}, which can be {@link OO.ui.MenuToolGroup menus} * of tools, {@link OO.ui.ListToolGroup lists} of tools, or a single {@link OO.ui.BarToolGroup bar} of tools. * The arrangement and order of the toolgroups is customized when the toolbar is set up. Tools can be presented in * any order, but each can only appear once in the toolbar. * * The toolbar can be synchronized with the state of the external "application", like a text * editor's editing area, marking tools as active/inactive (e.g. a 'bold' tool would be shown as * active when the text cursor was inside bolded text) or enabled/disabled (e.g. a table caption * tool would be disabled while the user is not editing a table). A state change is signalled by * emitting the {@link #event-updateState 'updateState' event}, which calls Tools' * {@link OO.ui.Tool#onUpdateState onUpdateState method}. * * The following is an example of a basic toolbar. * * @example * // Example of a toolbar * // Create the toolbar * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'Toolbar example' ); * * // Define the tools that we're going to place in our toolbar * * // Create a class inheriting from OO.ui.Tool * function SearchTool() { * SearchTool.parent.apply( this, arguments ); * } * OO.inheritClass( SearchTool, OO.ui.Tool ); * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one * // of 'icon' and 'title' (displayed icon and text). * SearchTool.static.name = 'search'; * SearchTool.static.icon = 'search'; * SearchTool.static.title = 'Search...'; * // Defines the action that will happen when this tool is selected (clicked). * SearchTool.prototype.onSelect = function () { * $area.text( 'Search tool clicked!' ); * // Never display this tool as "active" (selected). * this.setActive( false ); * }; * SearchTool.prototype.onUpdateState = function () {}; * // Make this tool available in our toolFactory and thus our toolbar * toolFactory.register( SearchTool ); * * // Register two more tools, nothing interesting here * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * $area.text( 'Settings tool clicked!' ); * this.setActive( false ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * * // Register two more tools, nothing interesting here * function StuffTool() { * StuffTool.parent.apply( this, arguments ); * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'ellipsis'; * StuffTool.static.title = 'More stuff'; * StuffTool.prototype.onSelect = function () { * $area.text( 'More stuff tool clicked!' ); * this.setActive( false ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a * // little popup window (a PopupWidget). * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * } * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * // 'bar' tool groups display tools' icons only, side-by-side. * type: 'bar', * include: [ 'search', 'help' ] * }, * { * // 'list' tool groups display both the titles and icons, in a dropdown list. * type: 'list', * indicator: 'down', * label: 'More', * include: [ 'settings', 'stuff' ] * } * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here, * // since it's more complicated to use. (See the next example snippet on this page.) * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( 'body' ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * toolbar.emit( 'updateState' ); * * The following example extends the previous one to illustrate 'menu' toolgroups and the usage of * {@link #event-updateState 'updateState' event}. * * @example * // Create the toolbar * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'Toolbar example' ); * * // Define the tools that we're going to place in our toolbar * * // Create a class inheriting from OO.ui.Tool * function SearchTool() { * SearchTool.parent.apply( this, arguments ); * } * OO.inheritClass( SearchTool, OO.ui.Tool ); * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one * // of 'icon' and 'title' (displayed icon and text). * SearchTool.static.name = 'search'; * SearchTool.static.icon = 'search'; * SearchTool.static.title = 'Search...'; * // Defines the action that will happen when this tool is selected (clicked). * SearchTool.prototype.onSelect = function () { * $area.text( 'Search tool clicked!' ); * // Never display this tool as "active" (selected). * this.setActive( false ); * }; * SearchTool.prototype.onUpdateState = function () {}; * // Make this tool available in our toolFactory and thus our toolbar * toolFactory.register( SearchTool ); * * // Register two more tools, nothing interesting here * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * $area.text( 'Settings tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * * // Register two more tools, nothing interesting here * function StuffTool() { * StuffTool.parent.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'ellipsis'; * StuffTool.static.title = 'More stuff'; * StuffTool.prototype.onSelect = function () { * $area.text( 'More stuff tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented. * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * } * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * // 'bar' tool groups display tools' icons only, side-by-side. * type: 'bar', * include: [ 'search', 'help' ] * }, * { * // 'menu' tool groups display both the titles and icons, in a dropdown menu. * // Menu label indicates which items are selected. * type: 'menu', * indicator: 'down', * include: [ 'settings', 'stuff' ] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( 'body' ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * toolbar.emit( 'updateState' ); * * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating toolgroups * @param {Object} [config] Configuration options * @cfg {boolean} [actions] Add an actions section to the toolbar. Actions are commands that are included * in the toolbar, but are not configured as tools. By default, actions are displayed on the right side of * the toolbar. * @cfg {string} [position='top'] Whether the toolbar is positioned above ('top') or below ('bottom') content. */ OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolFactory ) && config === undefined ) { config = toolFactory; toolFactory = config.toolFactory; toolGroupFactory = config.toolGroupFactory; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.Toolbar.parent.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); OO.ui.mixin.GroupElement.call( this, config ); // Properties this.toolFactory = toolFactory; this.toolGroupFactory = toolGroupFactory; this.groups = []; this.tools = {}; this.position = config.position || 'top'; this.$bar = $( '<div>' ); this.$actions = $( '<div>' ); this.initialized = false; this.narrowThreshold = null; this.onWindowResizeHandler = this.onWindowResize.bind( this ); // Events this.$element .add( this.$bar ).add( this.$group ).add( this.$actions ) .on( 'mousedown keydown', this.onPointerDown.bind( this ) ); // Initialization this.$group.addClass( 'oo-ui-toolbar-tools' ); if ( config.actions ) { this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) ); } this.$bar .addClass( 'oo-ui-toolbar-bar' ) .append( this.$group, '<div style="clear:both"></div>' ); this.$element.addClass( 'oo-ui-toolbar oo-ui-toolbar-position-' + this.position ).append( this.$bar ); }; /* Setup */ OO.inheritClass( OO.ui.Toolbar, OO.ui.Element ); OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter ); OO.mixinClass( OO.ui.Toolbar, OO.ui.mixin.GroupElement ); /* Events */ /** * @event updateState * * An 'updateState' event must be emitted on the Toolbar (by calling `toolbar.emit( 'updateState' )`) * every time the state of the application using the toolbar changes, and an update to the state of * tools is required. * * @param {...Mixed} data Application-defined parameters */ /* Methods */ /** * Get the tool factory. * * @return {OO.ui.ToolFactory} Tool factory */ OO.ui.Toolbar.prototype.getToolFactory = function () { return this.toolFactory; }; /** * Get the toolgroup factory. * * @return {OO.Factory} Toolgroup factory */ OO.ui.Toolbar.prototype.getToolGroupFactory = function () { return this.toolGroupFactory; }; /** * Handles mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.Toolbar.prototype.onPointerDown = function ( e ) { var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ), $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' ); if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) { return false; } }; /** * Handle window resize event. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.Toolbar.prototype.onWindowResize = function () { this.$element.toggleClass( 'oo-ui-toolbar-narrow', this.$bar.width() <= this.getNarrowThreshold() ); }; /** * Get the (lazily-computed) width threshold for applying the oo-ui-toolbar-narrow * class. * * @private * @return {number} Width threshold in pixels */ OO.ui.Toolbar.prototype.getNarrowThreshold = function () { if ( this.narrowThreshold === null ) { this.narrowThreshold = this.$group.width() + this.$actions.width(); } return this.narrowThreshold; }; /** * Sets up handles and preloads required information for the toolbar to work. * This must be called after it is attached to a visible document and before doing anything else. */ OO.ui.Toolbar.prototype.initialize = function () { if ( !this.initialized ) { this.initialized = true; $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler ); this.onWindowResize(); } }; /** * Set up the toolbar. * * The toolbar is set up with a list of toolgroup configurations that specify the type of * toolgroup ({@link OO.ui.BarToolGroup bar}, {@link OO.ui.MenuToolGroup menu}, or {@link OO.ui.ListToolGroup list}) * to add and which tools to include, exclude, promote, or demote within that toolgroup. Please * see {@link OO.ui.ToolGroup toolgroups} for more information about including tools in toolgroups. * * @param {Object.<string,Array>} groups List of toolgroup configurations * @param {Array|string} [groups.include] Tools to include in the toolgroup * @param {Array|string} [groups.exclude] Tools to exclude from the toolgroup * @param {Array|string} [groups.promote] Tools to promote to the beginning of the toolgroup * @param {Array|string} [groups.demote] Tools to demote to the end of the toolgroup */ OO.ui.Toolbar.prototype.setup = function ( groups ) { var i, len, type, group, items = [], defaultType = 'bar'; // Cleanup previous groups this.reset(); // Build out new groups for ( i = 0, len = groups.length; i < len; i++ ) { group = groups[ i ]; if ( group.include === '*' ) { // Apply defaults to catch-all groups if ( group.type === undefined ) { group.type = 'list'; } if ( group.label === undefined ) { group.label = OO.ui.msg( 'ooui-toolbar-more' ); } } // Check type has been registered type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType; items.push( this.getToolGroupFactory().create( type, this, group ) ); } this.addItems( items ); }; /** * Remove all tools and toolgroups from the toolbar. */ OO.ui.Toolbar.prototype.reset = function () { var i, len; this.groups = []; this.tools = {}; for ( i = 0, len = this.items.length; i < len; i++ ) { this.items[ i ].destroy(); } this.clearItems(); }; /** * Destroy the toolbar. * * Destroying the toolbar removes all event handlers and DOM elements that constitute the toolbar. Call * this method whenever you are done using a toolbar. */ OO.ui.Toolbar.prototype.destroy = function () { $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler ); this.reset(); this.$element.remove(); }; /** * Check if the tool is available. * * Available tools are ones that have not yet been added to the toolbar. * * @param {string} name Symbolic name of tool * @return {boolean} Tool is available */ OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) { return !this.tools[ name ]; }; /** * Prevent tool from being used again. * * @param {OO.ui.Tool} tool Tool to reserve */ OO.ui.Toolbar.prototype.reserveTool = function ( tool ) { this.tools[ tool.getName() ] = tool; }; /** * Allow tool to be used again. * * @param {OO.ui.Tool} tool Tool to release */ OO.ui.Toolbar.prototype.releaseTool = function ( tool ) { delete this.tools[ tool.getName() ]; }; /** * Get accelerator label for tool. * * The OOjs UI library does not contain an accelerator system, but this is the hook for one. To * use an accelerator system, subclass the toolbar and override this method, which is meant to return a label * that describes the accelerator keys for the tool passed (by symbolic name) to the method. * * @param {string} name Symbolic name of tool * @return {string|undefined} Tool accelerator label if available */ OO.ui.Toolbar.prototype.getToolAccelerator = function () { return undefined; }; /** * Tools, together with {@link OO.ui.ToolGroup toolgroups}, constitute {@link OO.ui.Toolbar toolbars}. * Each tool is configured with a static name, title, and icon and is customized with the command to carry * out when the tool is selected. Tools must also be registered with a {@link OO.ui.ToolFactory tool factory}, * which creates the tools on demand. * * Every Tool subclass must implement two methods: * * - {@link #onUpdateState} * - {@link #onSelect} * * Tools are added to toolgroups ({@link OO.ui.ListToolGroup ListToolGroup}, * {@link OO.ui.BarToolGroup BarToolGroup}, or {@link OO.ui.MenuToolGroup MenuToolGroup}), which determine how * the tool is displayed in the toolbar. See {@link OO.ui.Toolbar toolbars} for an example. * * For more information, please see the [OOjs UI documentation on MediaWiki][1]. * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options * @cfg {string|Function} [title] Title text or a function that returns text. If this config is omitted, the value of * the {@link #static-title static title} property is used. * * The title is used in different ways depending on the type of toolgroup that contains the tool. The * title is used as a tooltip if the tool is part of a {@link OO.ui.BarToolGroup bar} toolgroup, or as the label text if the tool is * part of a {@link OO.ui.ListToolGroup list} or {@link OO.ui.MenuToolGroup menu} toolgroup. * * For bar toolgroups, a description of the accelerator key is appended to the title if an accelerator key * is associated with an action by the same name as the tool and accelerator functionality has been added to the application. * To add accelerator key functionality, you must subclass OO.ui.Toolbar and override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method. */ OO.ui.Tool = function OoUiTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.Tool.parent.call( this, config ); // Properties this.toolGroup = toolGroup; this.toolbar = this.toolGroup.getToolbar(); this.active = false; this.$title = $( '<span>' ); this.$accel = $( '<span>' ); this.$link = $( '<a>' ); this.title = null; // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$link } ) ); // Events this.toolbar.connect( this, { updateState: 'onUpdateState' } ); // Initialization this.$title.addClass( 'oo-ui-tool-title' ); this.$accel .addClass( 'oo-ui-tool-accel' ) .prop( { // This may need to be changed if the key names are ever localized, // but for now they are essentially written in English dir: 'ltr', lang: 'en' } ); this.$link .addClass( 'oo-ui-tool-link' ) .append( this.$icon, this.$title, this.$accel ) .attr( 'role', 'button' ); this.$element .data( 'oo-ui-tool', this ) .addClass( 'oo-ui-tool ' + 'oo-ui-tool-name-' + this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' ) ) .toggleClass( 'oo-ui-tool-with-label', this.constructor.static.displayBothIconAndLabel ) .append( this.$link ); this.setTitle( config.title || this.constructor.static.title ); }; /* Setup */ OO.inheritClass( OO.ui.Tool, OO.ui.Widget ); OO.mixinClass( OO.ui.Tool, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.Tool, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.Tool, OO.ui.mixin.TabIndexedElement ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.Tool.static.tagName = 'span'; /** * Symbolic name of tool. * * The symbolic name is used internally to register the tool with a {@link OO.ui.ToolFactory ToolFactory}. It can * also be used when adding tools to toolgroups. * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Tool.static.name = ''; /** * Symbolic name of the group. * * The group name is used to associate tools with each other so that they can be selected later by * a {@link OO.ui.ToolGroup toolgroup}. * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Tool.static.group = ''; /** * Tool title text or a function that returns title text. The value of the static property is overridden if the #title config option is used. * * @abstract * @static * @inheritable * @property {string|Function} */ OO.ui.Tool.static.title = ''; /** * Display both icon and label when the tool is used in a {@link OO.ui.BarToolGroup bar} toolgroup. * Normally only the icon is displayed, or only the label if no icon is given. * * @static * @inheritable * @property {boolean} */ OO.ui.Tool.static.displayBothIconAndLabel = false; /** * Add tool to catch-all groups automatically. * * A catch-all group, which contains all tools that do not currently belong to a toolgroup, * can be included in a toolgroup using the wildcard selector, an asterisk (*). * * @static * @inheritable * @property {boolean} */ OO.ui.Tool.static.autoAddToCatchall = true; /** * Add tool to named groups automatically. * * By default, tools that are configured with a static ‘group’ property are added * to that group and will be selected when the symbolic name of the group is specified (e.g., when * toolgroups include tools by group name). * * @static * @property {boolean} * @inheritable */ OO.ui.Tool.static.autoAddToGroup = true; /** * Check if this tool is compatible with given data. * * This is a stub that can be overridden to provide support for filtering tools based on an * arbitrary piece of information (e.g., where the cursor is in a document). The implementation * must also call this method so that the compatibility check can be performed. * * @static * @inheritable * @param {Mixed} data Data to check * @return {boolean} Tool can be used with data */ OO.ui.Tool.static.isCompatibleWith = function () { return false; }; /* Methods */ /** * Handle the toolbar state being updated. This method is called when the * {@link OO.ui.Toolbar#event-updateState 'updateState' event} is emitted on the * {@link OO.ui.Toolbar Toolbar} that uses this tool, and should set the state of this tool * depending on application state (usually by calling #setDisabled to enable or disable the tool, * or #setActive to mark is as currently in-use or not). * * This is an abstract method that must be overridden in a concrete subclass. * * @method * @protected * @abstract */ OO.ui.Tool.prototype.onUpdateState = null; /** * Handle the tool being selected. This method is called when the user triggers this tool, * usually by clicking on its label/icon. * * This is an abstract method that must be overridden in a concrete subclass. * * @method * @protected * @abstract */ OO.ui.Tool.prototype.onSelect = null; /** * Check if the tool is active. * * Tools become active when their #onSelect or #onUpdateState handlers change them to appear pressed * with the #setActive method. Additional CSS is applied to the tool to reflect the active state. * * @return {boolean} Tool is active */ OO.ui.Tool.prototype.isActive = function () { return this.active; }; /** * Make the tool appear active or inactive. * * This method should be called within #onSelect or #onUpdateState event handlers to make the tool * appear pressed or not. * * @param {boolean} state Make tool appear active */ OO.ui.Tool.prototype.setActive = function ( state ) { this.active = !!state; if ( this.active ) { this.$element.addClass( 'oo-ui-tool-active' ); this.setFlags( { progressive: true } ); } else { this.$element.removeClass( 'oo-ui-tool-active' ); this.setFlags( { progressive: false } ); } }; /** * Set the tool #title. * * @param {string|Function} title Title text or a function that returns text * @chainable */ OO.ui.Tool.prototype.setTitle = function ( title ) { this.title = OO.ui.resolveMsg( title ); this.updateTitle(); return this; }; /** * Get the tool #title. * * @return {string} Title text */ OO.ui.Tool.prototype.getTitle = function () { return this.title; }; /** * Get the tool's symbolic name. * * @return {string} Symbolic name of tool */ OO.ui.Tool.prototype.getName = function () { return this.constructor.static.name; }; /** * Update the title. */ OO.ui.Tool.prototype.updateTitle = function () { var titleTooltips = this.toolGroup.constructor.static.titleTooltips, accelTooltips = this.toolGroup.constructor.static.accelTooltips, accel = this.toolbar.getToolAccelerator( this.constructor.static.name ), tooltipParts = []; this.$title.text( this.title ); this.$accel.text( accel ); if ( titleTooltips && typeof this.title === 'string' && this.title.length ) { tooltipParts.push( this.title ); } if ( accelTooltips && typeof accel === 'string' && accel.length ) { tooltipParts.push( accel ); } if ( tooltipParts.length ) { this.$link.attr( 'title', tooltipParts.join( ' ' ) ); } else { this.$link.removeAttr( 'title' ); } }; /** * Destroy tool. * * Destroying the tool removes all event handlers and the tool’s DOM elements. * Call this method whenever you are done using a tool. */ OO.ui.Tool.prototype.destroy = function () { this.toolbar.disconnect( this ); this.$element.remove(); }; /** * ToolGroups are collections of {@link OO.ui.Tool tools} that are used in a {@link OO.ui.Toolbar toolbar}. * The type of toolgroup ({@link OO.ui.ListToolGroup list}, {@link OO.ui.BarToolGroup bar}, or {@link OO.ui.MenuToolGroup menu}) * to which a tool belongs determines how the tool is arranged and displayed in the toolbar. Toolgroups * themselves are created on demand with a {@link OO.ui.ToolGroupFactory toolgroup factory}. * * Toolgroups can contain individual tools, groups of tools, or all available tools, as specified * using the `include` config option. See OO.ui.ToolFactory#extract on documentation of the format. * The options `exclude`, `promote`, and `demote` support the same formats. * * See {@link OO.ui.Toolbar toolbars} for a full example. For more information about toolbars in general, * please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {Array|string} [include] List of tools to include in the toolgroup, see above. * @cfg {Array|string} [exclude] List of tools to exclude from the toolgroup, see above. * @cfg {Array|string} [promote] List of tools to promote to the beginning of the toolgroup, see above. * @cfg {Array|string} [demote] List of tools to demote to the end of the toolgroup, see above. * This setting is particularly useful when tools have been added to the toolgroup * en masse (e.g., via the catch-all selector). */ OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.ToolGroup.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, config ); // Properties this.toolbar = toolbar; this.tools = {}; this.pressed = null; this.autoDisabled = false; this.include = config.include || []; this.exclude = config.exclude || []; this.promote = config.promote || []; this.demote = config.demote || []; this.onCapturedMouseKeyUpHandler = this.onCapturedMouseKeyUp.bind( this ); // Events this.$element.on( { mousedown: this.onMouseKeyDown.bind( this ), mouseup: this.onMouseKeyUp.bind( this ), keydown: this.onMouseKeyDown.bind( this ), keyup: this.onMouseKeyUp.bind( this ), focus: this.onMouseOverFocus.bind( this ), blur: this.onMouseOutBlur.bind( this ), mouseover: this.onMouseOverFocus.bind( this ), mouseout: this.onMouseOutBlur.bind( this ) } ); this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } ); this.aggregate( { disable: 'itemDisable' } ); this.connect( this, { itemDisable: 'updateDisabled' } ); // Initialization this.$group.addClass( 'oo-ui-toolGroup-tools' ); this.$element .addClass( 'oo-ui-toolGroup' ) .append( this.$group ); this.populate(); }; /* Setup */ OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget ); OO.mixinClass( OO.ui.ToolGroup, OO.ui.mixin.GroupElement ); /* Events */ /** * @event update */ /* Static Properties */ /** * Show labels in tooltips. * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.titleTooltips = false; /** * Show acceleration labels in tooltips. * * Note: The OOjs UI library does not include an accelerator system, but does contain * a hook for one. To use an accelerator system, subclass the {@link OO.ui.Toolbar toolbar} and * override the {@link OO.ui.Toolbar#getToolAccelerator getToolAccelerator} method, which is * meant to return a label that describes the accelerator keys for a given tool (e.g., 'Ctrl + M'). * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.accelTooltips = false; /** * Automatically disable the toolgroup when all tools are disabled * * @static * @inheritable * @property {boolean} */ OO.ui.ToolGroup.static.autoDisable = true; /** * @abstract * @static * @inheritable * @property {string} */ OO.ui.ToolGroup.static.name = null; /* Methods */ /** * @inheritdoc */ OO.ui.ToolGroup.prototype.isDisabled = function () { return this.autoDisabled || OO.ui.ToolGroup.parent.prototype.isDisabled.apply( this, arguments ); }; /** * @inheritdoc */ OO.ui.ToolGroup.prototype.updateDisabled = function () { var i, item, allDisabled = true; if ( this.constructor.static.autoDisable ) { for ( i = this.items.length - 1; i >= 0; i-- ) { item = this.items[ i ]; if ( !item.isDisabled() ) { allDisabled = false; break; } } this.autoDisabled = allDisabled; } OO.ui.ToolGroup.parent.prototype.updateDisabled.apply( this, arguments ); }; /** * Handle mouse down and key down events. * * @protected * @param {jQuery.Event} e Mouse down or key down event */ OO.ui.ToolGroup.prototype.onMouseKeyDown = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.pressed = this.getTargetTool( e ); if ( this.pressed ) { this.pressed.setActive( true ); this.getElementDocument().addEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true ); this.getElementDocument().addEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true ); } return false; } }; /** * Handle captured mouse up and key up events. * * @protected * @param {MouseEvent|KeyboardEvent} e Mouse up or key up event */ OO.ui.ToolGroup.prototype.onCapturedMouseKeyUp = function ( e ) { this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseKeyUpHandler, true ); this.getElementDocument().removeEventListener( 'keyup', this.onCapturedMouseKeyUpHandler, true ); // onMouseKeyUp may be called a second time, depending on where the mouse is when the button is // released, but since `this.pressed` will no longer be true, the second call will be ignored. this.onMouseKeyUp( e ); }; /** * Handle mouse up and key up events. * * @protected * @param {MouseEvent|KeyboardEvent} e Mouse up or key up event */ OO.ui.ToolGroup.prototype.onMouseKeyUp = function ( e ) { var tool = this.getTargetTool( e ); if ( !this.isDisabled() && this.pressed && this.pressed === tool && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.pressed.onSelect(); this.pressed = null; e.preventDefault(); e.stopPropagation(); } this.pressed = null; }; /** * Handle mouse over and focus events. * * @protected * @param {jQuery.Event} e Mouse over or focus event */ OO.ui.ToolGroup.prototype.onMouseOverFocus = function ( e ) { var tool = this.getTargetTool( e ); if ( this.pressed && this.pressed === tool ) { this.pressed.setActive( true ); } }; /** * Handle mouse out and blur events. * * @protected * @param {jQuery.Event} e Mouse out or blur event */ OO.ui.ToolGroup.prototype.onMouseOutBlur = function ( e ) { var tool = this.getTargetTool( e ); if ( this.pressed && this.pressed === tool ) { this.pressed.setActive( false ); } }; /** * Get the closest tool to a jQuery.Event. * * Only tool links are considered, which prevents other elements in the tool such as popups from * triggering tool group interactions. * * @private * @param {jQuery.Event} e * @return {OO.ui.Tool|null} Tool, `null` if none was found */ OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) { var tool, $item = $( e.target ).closest( '.oo-ui-tool-link' ); if ( $item.length ) { tool = $item.parent().data( 'oo-ui-tool' ); } return tool && !tool.isDisabled() ? tool : null; }; /** * Handle tool registry register events. * * If a tool is registered after the group is created, we must repopulate the list to account for: * * - a tool being added that may be included * - a tool already included being overridden * * @protected * @param {string} name Symbolic name of tool */ OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () { this.populate(); }; /** * Get the toolbar that contains the toolgroup. * * @return {OO.ui.Toolbar} Toolbar that contains the toolgroup */ OO.ui.ToolGroup.prototype.getToolbar = function () { return this.toolbar; }; /** * Add and remove tools based on configuration. */ OO.ui.ToolGroup.prototype.populate = function () { var i, len, name, tool, toolFactory = this.toolbar.getToolFactory(), names = {}, add = [], remove = [], list = this.toolbar.getToolFactory().getTools( this.include, this.exclude, this.promote, this.demote ); // Build a list of needed tools for ( i = 0, len = list.length; i < len; i++ ) { name = list[ i ]; if ( // Tool exists toolFactory.lookup( name ) && // Tool is available or is already in this group ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] ) ) { // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before // creating it, but we can't call reserveTool() yet because we haven't created the tool. this.toolbar.tools[ name ] = true; tool = this.tools[ name ]; if ( !tool ) { // Auto-initialize tools on first use this.tools[ name ] = tool = toolFactory.create( name, this ); tool.updateTitle(); } this.toolbar.reserveTool( tool ); add.push( tool ); names[ name ] = true; } } // Remove tools that are no longer needed for ( name in this.tools ) { if ( !names[ name ] ) { this.tools[ name ].destroy(); this.toolbar.releaseTool( this.tools[ name ] ); remove.push( this.tools[ name ] ); delete this.tools[ name ]; } } if ( remove.length ) { this.removeItems( remove ); } // Update emptiness state if ( add.length ) { this.$element.removeClass( 'oo-ui-toolGroup-empty' ); } else { this.$element.addClass( 'oo-ui-toolGroup-empty' ); } // Re-add tools (moving existing ones to new locations) this.addItems( add ); // Disabled state may depend on items this.updateDisabled(); }; /** * Destroy toolgroup. */ OO.ui.ToolGroup.prototype.destroy = function () { var name; this.clearItems(); this.toolbar.getToolFactory().disconnect( this ); for ( name in this.tools ) { this.toolbar.releaseTool( this.tools[ name ] ); this.tools[ name ].disconnect( this ).destroy(); delete this.tools[ name ]; } this.$element.remove(); }; /** * A ToolFactory creates tools on demand. All tools ({@link OO.ui.Tool Tools}, {@link OO.ui.PopupTool PopupTools}, * and {@link OO.ui.ToolGroupTool ToolGroupTools}) must be registered with a tool factory. Tools are * registered by their symbolic name. See {@link OO.ui.Toolbar toolbars} for an example. * * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.Factory * @constructor */ OO.ui.ToolFactory = function OoUiToolFactory() { // Parent constructor OO.ui.ToolFactory.parent.call( this ); }; /* Setup */ OO.inheritClass( OO.ui.ToolFactory, OO.Factory ); /* Methods */ /** * Get tools from the factory * * @param {Array|string} [include] Included tools, see #extract for format * @param {Array|string} [exclude] Excluded tools, see #extract for format * @param {Array|string} [promote] Promoted tools, see #extract for format * @param {Array|string} [demote] Demoted tools, see #extract for format * @return {string[]} List of tools */ OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) { var i, len, included, promoted, demoted, auto = [], used = {}; // Collect included and not excluded tools included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) ); // Promotion promoted = this.extract( promote, used ); demoted = this.extract( demote, used ); // Auto for ( i = 0, len = included.length; i < len; i++ ) { if ( !used[ included[ i ] ] ) { auto.push( included[ i ] ); } } return promoted.concat( auto ).concat( demoted ); }; /** * Get a flat list of names from a list of names or groups. * * Normally, `collection` is an array of tool specifications. Tools can be specified in the * following ways: * * - To include an individual tool, use the symbolic name: `{ name: 'tool-name' }` or `'tool-name'`. * - To include all tools in a group, use the group name: `{ group: 'group-name' }`. (To assign the * tool to a group, use OO.ui.Tool.static.group.) * * Alternatively, to include all tools that are not yet assigned to any other toolgroup, use the * catch-all selector `'*'`. * * If `used` is passed, tool names that appear as properties in this object will be considered * already assigned, and will not be returned even if specified otherwise. The tool names extracted * by this function call will be added as new properties in the object. * * @private * @param {Array|string} collection List of tools, see above * @param {Object} [used] Object containing information about used tools, see above * @return {string[]} List of extracted tool names */ OO.ui.ToolFactory.prototype.extract = function ( collection, used ) { var i, len, item, name, tool, names = []; collection = !Array.isArray( collection ) ? [ collection ] : collection; for ( i = 0, len = collection.length; i < len; i++ ) { item = collection[ i ]; if ( item === '*' ) { for ( name in this.registry ) { tool = this.registry[ name ]; if ( // Only add tools by group name when auto-add is enabled tool.static.autoAddToCatchall && // Exclude already used tools ( !used || !used[ name ] ) ) { names.push( name ); if ( used ) { used[ name ] = true; } } } } else { // Allow plain strings as shorthand for named tools if ( typeof item === 'string' ) { item = { name: item }; } if ( OO.isPlainObject( item ) ) { if ( item.group ) { for ( name in this.registry ) { tool = this.registry[ name ]; if ( // Include tools with matching group tool.static.group === item.group && // Only add tools by group name when auto-add is enabled tool.static.autoAddToGroup && // Exclude already used tools ( !used || !used[ name ] ) ) { names.push( name ); if ( used ) { used[ name ] = true; } } } // Include tools with matching name and exclude already used tools } else if ( item.name && ( !used || !used[ item.name ] ) ) { names.push( item.name ); if ( used ) { used[ item.name ] = true; } } } } } return names; }; /** * ToolGroupFactories create {@link OO.ui.ToolGroup toolgroups} on demand. The toolgroup classes must * specify a symbolic name and be registered with the factory. The following classes are registered by * default: * * - {@link OO.ui.BarToolGroup BarToolGroups} (‘bar’) * - {@link OO.ui.MenuToolGroup MenuToolGroups} (‘menu’) * - {@link OO.ui.ListToolGroup ListToolGroups} (‘list’) * * See {@link OO.ui.Toolbar toolbars} for an example. * * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.Factory * @constructor */ OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() { var i, l, defaultClasses; // Parent constructor OO.Factory.call( this ); defaultClasses = this.constructor.static.getDefaultClasses(); // Register default toolgroups for ( i = 0, l = defaultClasses.length; i < l; i++ ) { this.register( defaultClasses[ i ] ); } }; /* Setup */ OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory ); /* Static Methods */ /** * Get a default set of classes to be registered on construction. * * @return {Function[]} Default classes */ OO.ui.ToolGroupFactory.static.getDefaultClasses = function () { return [ OO.ui.BarToolGroup, OO.ui.ListToolGroup, OO.ui.MenuToolGroup ]; }; /** * Popup tools open a popup window when they are selected from the {@link OO.ui.Toolbar toolbar}. Each popup tool is configured * with a static name, title, and icon, as well with as any popup configurations. Unlike other tools, popup tools do not require that developers specify * an #onSelect or #onUpdateState method, as these methods have been implemented already. * * // Example of a popup tool. When selected, a popup tool displays * // a popup window. * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * }; * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * For an example of a toolbar that contains a popup tool, see {@link OO.ui.Toolbar toolbars}. For more information about * toolbars in genreral, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @abstract * @class * @extends OO.ui.Tool * @mixins OO.ui.mixin.PopupElement * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options */ OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Parent constructor OO.ui.PopupTool.parent.call( this, toolGroup, config ); // Mixin constructors OO.ui.mixin.PopupElement.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-popupTool' ) .append( this.popup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool ); OO.mixinClass( OO.ui.PopupTool, OO.ui.mixin.PopupElement ); /* Methods */ /** * Handle the tool being selected. * * @inheritdoc */ OO.ui.PopupTool.prototype.onSelect = function () { if ( !this.isDisabled() ) { this.popup.toggle(); } this.setActive( false ); return false; }; /** * Handle the toolbar state being updated. * * @inheritdoc */ OO.ui.PopupTool.prototype.onUpdateState = function () { this.setActive( false ); }; /** * A ToolGroupTool is a special sort of tool that can contain other {@link OO.ui.Tool tools} * and {@link OO.ui.ToolGroup toolgroups}. The ToolGroupTool was specifically designed to be used * inside a {@link OO.ui.BarToolGroup bar} toolgroup to provide access to additional tools from * the bar item. Included tools will be displayed in a dropdown {@link OO.ui.ListToolGroup list} * when the ToolGroupTool is selected. * * // Example: ToolGroupTool with two nested tools, 'setting1' and 'setting2', defined elsewhere. * * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * }; * OO.inheritClass( SettingsTool, OO.ui.ToolGroupTool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.static.groupConfig = { * icon: 'settings', * label: 'ToolGroupTool', * include: [ 'setting1', 'setting2' ] * }; * toolFactory.register( SettingsTool ); * * For more information, please see the [OOjs UI documentation on MediaWiki][1]. * * Please note that this implementation is subject to change per [T74159] [2]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars#ToolGroupTool * [2]: https://phabricator.wikimedia.org/T74159 * * @abstract * @class * @extends OO.ui.Tool * * @constructor * @param {OO.ui.ToolGroup} toolGroup * @param {Object} [config] Configuration options */ OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolGroup ) && config === undefined ) { config = toolGroup; toolGroup = config.toolGroup; } // Parent constructor OO.ui.ToolGroupTool.parent.call( this, toolGroup, config ); // Properties this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig ); // Events this.innerToolGroup.connect( this, { disable: 'onToolGroupDisable' } ); // Initialization this.$link.remove(); this.$element .addClass( 'oo-ui-toolGroupTool' ) .append( this.innerToolGroup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool ); /* Static Properties */ /** * Toolgroup configuration. * * The toolgroup configuration consists of the tools to include, as well as an icon and label * to use for the bar item. Tools can be included by symbolic name, group, or with the * wildcard selector. Please see {@link OO.ui.ToolGroup toolgroup} for more information. * * @property {Object.<string,Array>} */ OO.ui.ToolGroupTool.static.groupConfig = {}; /* Methods */ /** * Handle the tool being selected. * * @inheritdoc */ OO.ui.ToolGroupTool.prototype.onSelect = function () { this.innerToolGroup.setActive( !this.innerToolGroup.active ); return false; }; /** * Synchronize disabledness state of the tool with the inner toolgroup. * * @private * @param {boolean} disabled Element is disabled */ OO.ui.ToolGroupTool.prototype.onToolGroupDisable = function ( disabled ) { this.setDisabled( disabled ); }; /** * Handle the toolbar state being updated. * * @inheritdoc */ OO.ui.ToolGroupTool.prototype.onUpdateState = function () { this.setActive( false ); }; /** * Build a {@link OO.ui.ToolGroup toolgroup} from the specified configuration. * * @param {Object.<string,Array>} group Toolgroup configuration. Please see {@link OO.ui.ToolGroup toolgroup} for * more information. * @return {OO.ui.ListToolGroup} */ OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) { if ( group.include === '*' ) { // Apply defaults to catch-all groups if ( group.label === undefined ) { group.label = OO.ui.msg( 'ooui-toolbar-more' ); } } return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group ); }; /** * BarToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup} * and {@link OO.ui.ListToolGroup ListToolGroup}). The {@link OO.ui.Tool tools} in a BarToolGroup are * displayed by icon in a single row. The title of the tool is displayed when users move the mouse over * the tool. * * BarToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar is * set up. * * @example * // Example of a BarToolGroup with two tools * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'Example of a BarToolGroup with two tools.' ); * * // Define the tools that we're going to place in our toolbar * * // Create a class inheriting from OO.ui.Tool * function SearchTool() { * SearchTool.parent.apply( this, arguments ); * } * OO.inheritClass( SearchTool, OO.ui.Tool ); * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one * // of 'icon' and 'title' (displayed icon and text). * SearchTool.static.name = 'search'; * SearchTool.static.icon = 'search'; * SearchTool.static.title = 'Search...'; * // Defines the action that will happen when this tool is selected (clicked). * SearchTool.prototype.onSelect = function () { * $area.text( 'Search tool clicked!' ); * // Never display this tool as "active" (selected). * this.setActive( false ); * }; * SearchTool.prototype.onUpdateState = function () {}; * // Make this tool available in our toolFactory and thus our toolbar * toolFactory.register( SearchTool ); * * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a * // little popup window (a PopupWidget). * function HelpTool( toolGroup, config ) { * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: { * padded: true, * label: 'Help', * head: true * } }, config ) ); * this.popup.$body.append( '<p>I am helpful!</p>' ); * } * OO.inheritClass( HelpTool, OO.ui.PopupTool ); * HelpTool.static.name = 'help'; * HelpTool.static.icon = 'help'; * HelpTool.static.title = 'Help'; * toolFactory.register( HelpTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * // 'bar' tool groups display tools by icon only * type: 'bar', * include: [ 'search', 'help' ] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( 'body' ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * * For more information about how to add tools to a bar tool group, please see {@link OO.ui.ToolGroup toolgroup}. * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.ui.ToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options */ OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Parent constructor OO.ui.BarToolGroup.parent.call( this, toolbar, config ); // Initialization this.$element.addClass( 'oo-ui-barToolGroup' ); }; /* Setup */ OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.BarToolGroup.static.titleTooltips = true; /** * @static * @inheritdoc */ OO.ui.BarToolGroup.static.accelTooltips = true; /** * @static * @inheritdoc */ OO.ui.BarToolGroup.static.name = 'bar'; /** * PopupToolGroup is an abstract base class used by both {@link OO.ui.MenuToolGroup MenuToolGroup} * and {@link OO.ui.ListToolGroup ListToolGroup} to provide a popup--an overlaid menu or list of tools with an * optional icon and label. This class can be used for other base classes that also use this functionality. * * @abstract * @class * @extends OO.ui.ToolGroup * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.ClippableElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {string} [header] Text to display at the top of the popup */ OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = $.extend( { indicator: toolbar.position === 'bottom' ? 'up' : 'down' }, config ); // Parent constructor OO.ui.PopupToolGroup.parent.call( this, toolbar, config ); // Properties this.active = false; this.dragging = false; this.onBlurHandler = this.onBlur.bind( this ); this.$handle = $( '<span>' ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, config ); OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) ); // Events this.$handle.on( { keydown: this.onHandleMouseKeyDown.bind( this ), keyup: this.onHandleMouseKeyUp.bind( this ), mousedown: this.onHandleMouseKeyDown.bind( this ), mouseup: this.onHandleMouseKeyUp.bind( this ) } ); // Initialization this.$handle .addClass( 'oo-ui-popupToolGroup-handle' ) .append( this.$icon, this.$label, this.$indicator ); // If the pop-up should have a header, add it to the top of the toolGroup. // Note: If this feature is useful for other widgets, we could abstract it into an // OO.ui.HeaderedElement mixin constructor. if ( config.header !== undefined ) { this.$group .prepend( $( '<span>' ) .addClass( 'oo-ui-popupToolGroup-header' ) .text( config.header ) ); } this.$element .addClass( 'oo-ui-popupToolGroup' ) .prepend( this.$handle ); }; /* Setup */ OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.ClippableElement ); OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * @inheritdoc */ OO.ui.PopupToolGroup.prototype.setDisabled = function () { // Parent method OO.ui.PopupToolGroup.parent.prototype.setDisabled.apply( this, arguments ); if ( this.isDisabled() && this.isElementAttached() ) { this.setActive( false ); } }; /** * Handle focus being lost. * * The event is actually generated from a mouseup/keyup, so it is not a normal blur event object. * * @protected * @param {MouseEvent|KeyboardEvent} e Mouse up or key up event */ OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) { // Only deactivate when clicking outside the dropdown element if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) { this.setActive( false ); } }; /** * @inheritdoc */ OO.ui.PopupToolGroup.prototype.onMouseKeyUp = function ( e ) { // Only close toolgroup when a tool was actually selected if ( !this.isDisabled() && this.pressed && this.pressed === this.getTargetTool( e ) && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.setActive( false ); } return OO.ui.PopupToolGroup.parent.prototype.onMouseKeyUp.call( this, e ); }; /** * Handle mouse up and key up events. * * @protected * @param {jQuery.Event} e Mouse up or key up event */ OO.ui.PopupToolGroup.prototype.onHandleMouseKeyUp = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { return false; } }; /** * Handle mouse down and key down events. * * @protected * @param {jQuery.Event} e Mouse down or key down event */ OO.ui.PopupToolGroup.prototype.onHandleMouseKeyDown = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { this.setActive( !this.active ); return false; } }; /** * Switch into 'active' mode. * * When active, the popup is visible. A mouseup event anywhere in the document will trigger * deactivation. * * @param {boolean} value The active state to set */ OO.ui.PopupToolGroup.prototype.setActive = function ( value ) { var containerWidth, containerLeft; value = !!value; if ( this.active !== value ) { this.active = value; if ( value ) { this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true ); this.getElementDocument().addEventListener( 'keyup', this.onBlurHandler, true ); this.$clippable.css( 'left', '' ); // Try anchoring the popup to the left first this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' ); this.toggleClipping( true ); if ( this.isClippedHorizontally() ) { // Anchoring to the left caused the popup to clip, so anchor it to the right instead this.toggleClipping( false ); this.$element .removeClass( 'oo-ui-popupToolGroup-left' ) .addClass( 'oo-ui-popupToolGroup-right' ); this.toggleClipping( true ); } if ( this.isClippedHorizontally() ) { // Anchoring to the right also caused the popup to clip, so just make it fill the container containerWidth = this.$clippableScrollableContainer.width(); containerLeft = this.$clippableScrollableContainer.offset().left; this.toggleClipping( false ); this.$element.removeClass( 'oo-ui-popupToolGroup-right' ); this.$clippable.css( { left: -( this.$element.offset().left - containerLeft ), width: containerWidth } ); } } else { this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true ); this.getElementDocument().removeEventListener( 'keyup', this.onBlurHandler, true ); this.$element.removeClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right' ); this.toggleClipping( false ); } } }; /** * ListToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.MenuToolGroup MenuToolGroup} * and {@link OO.ui.BarToolGroup BarToolGroup}). The {@link OO.ui.Tool tools} in a ListToolGroup are displayed * by label in a dropdown menu. The title of the tool is used as the label text. The menu itself can be configured * with a label, icon, indicator, header, and title. * * ListToolGroups can be configured to be expanded and collapsed. Collapsed lists will have a ‘More’ option that * users can select to see the full list of tools. If a collapsed toolgroup is expanded, a ‘Fewer’ option permits * users to collapse the list again. * * ListToolGroups are created by a {@link OO.ui.ToolGroupFactory toolgroup factory} when the toolbar is set up. The factory * requires the ListToolGroup's symbolic name, 'list', which is specified along with the other configurations. For more * information about how to add tools to a ListToolGroup, please see {@link OO.ui.ToolGroup toolgroup}. * * @example * // Example of a ListToolGroup * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // Configure and register two tools * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * this.setActive( false ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * // Register two more tools, nothing interesting here * function StuffTool() { * StuffTool.parent.apply( this, arguments ); * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'search'; * StuffTool.static.title = 'Change the world'; * StuffTool.prototype.onSelect = function () { * this.setActive( false ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * toolbar.setup( [ * { * // Configurations for list toolgroup. * type: 'list', * label: 'ListToolGroup', * icon: 'ellipsis', * title: 'This is the title, displayed when user moves the mouse over the list toolgroup', * header: 'This is the header', * include: [ 'settings', 'stuff' ], * allowCollapse: ['stuff'] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * frame.$element.append( * toolbar.$element * ); * $( 'body' ).append( frame.$element ); * // Build the toolbar. This must be done after the toolbar has been appended to the document. * toolbar.initialize(); * * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.ui.PopupToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options * @cfg {Array} [allowCollapse] Allow the specified tools to be collapsed. By default, collapsible tools * will only be displayed if users click the ‘More’ option displayed at the bottom of the list. If * the list is expanded, a ‘Fewer’ option permits users to collapse the list again. Any tools that * are included in the toolgroup, but are not designated as collapsible, will always be displayed. * To open a collapsible list in its expanded state, set #expanded to 'true'. * @cfg {Array} [forceExpand] Expand the specified tools. All other tools will be designated as collapsible. * Unless #expanded is set to true, the collapsible tools will be collapsed when the list is first opened. * @cfg {boolean} [expanded=false] Expand collapsible tools. This config is only relevant if tools have * been designated as collapsible. When expanded is set to true, all tools in the group will be displayed * when the list is first opened. Users can collapse the list with a ‘Fewer’ option at the bottom. */ OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Properties (must be set before parent constructor, which calls #populate) this.allowCollapse = config.allowCollapse; this.forceExpand = config.forceExpand; this.expanded = config.expanded !== undefined ? config.expanded : false; this.collapsibleTools = []; // Parent constructor OO.ui.ListToolGroup.parent.call( this, toolbar, config ); // Initialization this.$element.addClass( 'oo-ui-listToolGroup' ); }; /* Setup */ OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.ListToolGroup.static.name = 'list'; /* Methods */ /** * @inheritdoc */ OO.ui.ListToolGroup.prototype.populate = function () { var i, len, allowCollapse = []; OO.ui.ListToolGroup.parent.prototype.populate.call( this ); // Update the list of collapsible tools if ( this.allowCollapse !== undefined ) { allowCollapse = this.allowCollapse; } else if ( this.forceExpand !== undefined ) { allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand ); } this.collapsibleTools = []; for ( i = 0, len = allowCollapse.length; i < len; i++ ) { if ( this.tools[ allowCollapse[ i ] ] !== undefined ) { this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] ); } } // Keep at the end, even when tools are added this.$group.append( this.getExpandCollapseTool().$element ); this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 ); this.updateCollapsibleState(); }; /** * Get the expand/collapse tool for this group * * @return {OO.ui.Tool} Expand collapse tool */ OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () { var ExpandCollapseTool; if ( this.expandCollapseTool === undefined ) { ExpandCollapseTool = function () { ExpandCollapseTool.parent.apply( this, arguments ); }; OO.inheritClass( ExpandCollapseTool, OO.ui.Tool ); ExpandCollapseTool.prototype.onSelect = function () { this.toolGroup.expanded = !this.toolGroup.expanded; this.toolGroup.updateCollapsibleState(); this.setActive( false ); }; ExpandCollapseTool.prototype.onUpdateState = function () { // Do nothing. Tool interface requires an implementation of this function. }; ExpandCollapseTool.static.name = 'more-fewer'; this.expandCollapseTool = new ExpandCollapseTool( this ); } return this.expandCollapseTool; }; /** * @inheritdoc */ OO.ui.ListToolGroup.prototype.onMouseKeyUp = function ( e ) { // Do not close the popup when the user wants to show more/fewer tools if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length && ( e.which === OO.ui.MouseButtons.LEFT || e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { // HACK: Prevent the popup list from being hidden. Skip the PopupToolGroup implementation (which // hides the popup list when a tool is selected) and call ToolGroup's implementation directly. return OO.ui.ListToolGroup.parent.parent.prototype.onMouseKeyUp.call( this, e ); } else { return OO.ui.ListToolGroup.parent.prototype.onMouseKeyUp.call( this, e ); } }; OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () { var i, len; this.getExpandCollapseTool() .setIcon( this.expanded ? 'collapse' : 'expand' ) .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) ); for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) { this.collapsibleTools[ i ].toggle( this.expanded ); } }; /** * MenuToolGroups are one of three types of {@link OO.ui.ToolGroup toolgroups} that are used to * create {@link OO.ui.Toolbar toolbars} (the other types of groups are {@link OO.ui.BarToolGroup BarToolGroup} * and {@link OO.ui.ListToolGroup ListToolGroup}). MenuToolGroups contain selectable {@link OO.ui.Tool tools}, * which are displayed by label in a dropdown menu. The tool's title is used as the label text, and the * menu label is updated to reflect which tool or tools are currently selected. If no tools are selected, * the menu label is empty. The menu can be configured with an indicator, icon, title, and/or header. * * MenuToolGroups are created by a {@link OO.ui.ToolGroupFactory tool group factory} when the toolbar * is set up. * * @example * // Example of a MenuToolGroup * var toolFactory = new OO.ui.ToolFactory(); * var toolGroupFactory = new OO.ui.ToolGroupFactory(); * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory ); * * // We will be placing status text in this element when tools are used * var $area = $( '<p>' ).text( 'An example of a MenuToolGroup. Select a tool from the dropdown menu.' ); * * // Define the tools that we're going to place in our toolbar * * function SettingsTool() { * SettingsTool.parent.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( SettingsTool, OO.ui.Tool ); * SettingsTool.static.name = 'settings'; * SettingsTool.static.icon = 'settings'; * SettingsTool.static.title = 'Change settings'; * SettingsTool.prototype.onSelect = function () { * $area.text( 'Settings tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * SettingsTool.prototype.onUpdateState = function () {}; * toolFactory.register( SettingsTool ); * * function StuffTool() { * StuffTool.parent.apply( this, arguments ); * this.reallyActive = false; * } * OO.inheritClass( StuffTool, OO.ui.Tool ); * StuffTool.static.name = 'stuff'; * StuffTool.static.icon = 'ellipsis'; * StuffTool.static.title = 'More stuff'; * StuffTool.prototype.onSelect = function () { * $area.text( 'More stuff tool clicked!' ); * // Toggle the active state on each click * this.reallyActive = !this.reallyActive; * this.setActive( this.reallyActive ); * // To update the menu label * this.toolbar.emit( 'updateState' ); * }; * StuffTool.prototype.onUpdateState = function () {}; * toolFactory.register( StuffTool ); * * // Finally define which tools and in what order appear in the toolbar. Each tool may only be * // used once (but not all defined tools must be used). * toolbar.setup( [ * { * type: 'menu', * header: 'This is the (optional) header', * title: 'This is the (optional) title', * include: [ 'settings', 'stuff' ] * } * ] ); * * // Create some UI around the toolbar and place it in the document * var frame = new OO.ui.PanelLayout( { * expanded: false, * framed: true * } ); * var contentFrame = new OO.ui.PanelLayout( { * expanded: false, * padded: true * } ); * frame.$element.append( * toolbar.$element, * contentFrame.$element.append( $area ) * ); * $( 'body' ).append( frame.$element ); * * // Here is where the toolbar is actually built. This must be done after inserting it into the * // document. * toolbar.initialize(); * toolbar.emit( 'updateState' ); * * For more information about how to add tools to a MenuToolGroup, please see {@link OO.ui.ToolGroup toolgroup}. * For more information about toolbars in general, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Toolbars * * @class * @extends OO.ui.PopupToolGroup * * @constructor * @param {OO.ui.Toolbar} toolbar * @param {Object} [config] Configuration options */ OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( toolbar ) && config === undefined ) { config = toolbar; toolbar = config.toolbar; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.MenuToolGroup.parent.call( this, toolbar, config ); // Events this.toolbar.connect( this, { updateState: 'onUpdateState' } ); // Initialization this.$element.addClass( 'oo-ui-menuToolGroup' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.MenuToolGroup.static.name = 'menu'; /* Methods */ /** * Handle the toolbar state being updated. * * When the state changes, the title of each active item in the menu will be joined together and * used as a label for the group. The label will be empty if none of the items are active. * * @private */ OO.ui.MenuToolGroup.prototype.onUpdateState = function () { var name, labelTexts = []; for ( name in this.tools ) { if ( this.tools[ name ].isActive() ) { labelTexts.push( this.tools[ name ].getTitle() ); } } this.setLabel( labelTexts.join( ', ' ) || ' ' ); }; }( OO ) ); //# sourceMappingURL=oojs-ui-toolbars.js.map /*! * OOjs UI v0.19.3-pre (72b81a54a7) * https://www.mediawiki.org/wiki/OOjs_UI * * Copyright 2011–2017 OOjs UI Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2017-02-21T22:25:51Z */ ( function ( OO ) { 'use strict'; /** * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action. * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability * of the actions. * * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information * and examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets * * @class * @extends OO.ui.ButtonWidget * @mixins OO.ui.mixin.PendingElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’). * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method * for more information about setting modes. * @cfg {boolean} [framed=false] Render the action button with a frame */ OO.ui.ActionWidget = function OoUiActionWidget( config ) { // Configuration initialization config = $.extend( { framed: false }, config ); // Parent constructor OO.ui.ActionWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.PendingElement.call( this, config ); // Properties this.action = config.action || ''; this.modes = config.modes || []; this.width = 0; this.height = 0; // Initialization this.$element.addClass( 'oo-ui-actionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget ); OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement ); /* Events */ /** * A resize event is emitted when the size of the widget changes. * * @event resize */ /* Methods */ /** * Check if the action is configured to be available in the specified `mode`. * * @param {string} mode Name of mode * @return {boolean} The action is configured with the mode */ OO.ui.ActionWidget.prototype.hasMode = function ( mode ) { return this.modes.indexOf( mode ) !== -1; }; /** * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’). * * @return {string} */ OO.ui.ActionWidget.prototype.getAction = function () { return this.action; }; /** * Get the symbolic name of the mode or modes for which the action is configured to be available. * * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method. * Only actions that are configured to be avaiable in the current mode will be visible. All other actions * are hidden. * * @return {string[]} */ OO.ui.ActionWidget.prototype.getModes = function () { return this.modes.slice(); }; /** * Emit a resize event if the size has changed. * * @private * @chainable */ OO.ui.ActionWidget.prototype.propagateResize = function () { var width, height; if ( this.isElementAttached() ) { width = this.$element.width(); height = this.$element.height(); if ( width !== this.width || height !== this.height ) { this.width = width; this.height = height; this.emit( 'resize' ); } } return this; }; /** * @inheritdoc */ OO.ui.ActionWidget.prototype.setIcon = function () { // Mixin method OO.ui.mixin.IconElement.prototype.setIcon.apply( this, arguments ); this.propagateResize(); return this; }; /** * @inheritdoc */ OO.ui.ActionWidget.prototype.setLabel = function () { // Mixin method OO.ui.mixin.LabelElement.prototype.setLabel.apply( this, arguments ); this.propagateResize(); return this; }; /** * @inheritdoc */ OO.ui.ActionWidget.prototype.setFlags = function () { // Mixin method OO.ui.mixin.FlaggedElement.prototype.setFlags.apply( this, arguments ); this.propagateResize(); return this; }; /** * @inheritdoc */ OO.ui.ActionWidget.prototype.clearFlags = function () { // Mixin method OO.ui.mixin.FlaggedElement.prototype.clearFlags.apply( this, arguments ); this.propagateResize(); return this; }; /** * Toggle the visibility of the action button. * * @param {boolean} [show] Show button, omit to toggle visibility * @chainable */ OO.ui.ActionWidget.prototype.toggle = function () { // Parent method OO.ui.ActionWidget.parent.prototype.toggle.apply( this, arguments ); this.propagateResize(); return this; }; /* eslint-disable no-unused-vars */ /** * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them. * Actions can be made available for specific contexts (modes) and circumstances * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}. * * ActionSets contain two types of actions: * * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property. * - Other: Other actions include all non-special visible actions. * * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * * @example * // Example: An action set used in a process dialog * function MyProcessDialog( config ) { * MyProcessDialog.parent.call( this, config ); * } * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog ); * MyProcessDialog.static.title = 'An action set in a process dialog'; * MyProcessDialog.static.name = 'myProcessDialog'; * // An action set that uses modes ('edit' and 'help' mode, in this example). * MyProcessDialog.static.actions = [ * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] }, * { action: 'help', modes: 'edit', label: 'Help' }, * { modes: 'edit', label: 'Cancel', flags: 'safe' }, * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' } * ]; * * MyProcessDialog.prototype.initialize = function () { * MyProcessDialog.parent.prototype.initialize.apply( this, arguments ); * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' ); * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' ); * this.stackLayout = new OO.ui.StackLayout( { * items: [ this.panel1, this.panel2 ] * } ); * this.$body.append( this.stackLayout.$element ); * }; * MyProcessDialog.prototype.getSetupProcess = function ( data ) { * return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data ) * .next( function () { * this.actions.setMode( 'edit' ); * }, this ); * }; * MyProcessDialog.prototype.getActionProcess = function ( action ) { * if ( action === 'help' ) { * this.actions.setMode( 'help' ); * this.stackLayout.setItem( this.panel2 ); * } else if ( action === 'back' ) { * this.actions.setMode( 'edit' ); * this.stackLayout.setItem( this.panel1 ); * } else if ( action === 'continue' ) { * var dialog = this; * return new OO.ui.Process( function () { * dialog.close(); * } ); * } * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action ); * }; * MyProcessDialog.prototype.getBodyHeight = function () { * return this.panel1.$element.outerHeight( true ); * }; * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * var dialog = new MyProcessDialog( { * size: 'medium' * } ); * windowManager.addWindows( [ dialog ] ); * windowManager.openWindow( dialog ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets * * @abstract * @class * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ActionSet = function OoUiActionSet( config ) { // Configuration initialization config = config || {}; // Mixin constructors OO.EventEmitter.call( this ); // Properties this.list = []; this.categories = { actions: 'getAction', flags: 'getFlags', modes: 'getModes' }; this.categorized = {}; this.special = {}; this.others = []; this.organized = false; this.changing = false; this.changed = false; }; /* eslint-enable no-unused-vars */ /* Setup */ OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter ); /* Static Properties */ /** * Symbolic name of the flags used to identify special actions. Special actions are displayed in the * header of a {@link OO.ui.ProcessDialog process dialog}. * See the [OOjs UI documentation on MediaWiki][2] for more information and examples. * * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs * * @abstract * @static * @inheritable * @property {string} */ OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ]; /* Events */ /** * @event click * * A 'click' event is emitted when an action is clicked. * * @param {OO.ui.ActionWidget} action Action that was clicked */ /** * @event resize * * A 'resize' event is emitted when an action widget is resized. * * @param {OO.ui.ActionWidget} action Action that was resized */ /** * @event add * * An 'add' event is emitted when actions are {@link #method-add added} to the action set. * * @param {OO.ui.ActionWidget[]} added Actions added */ /** * @event remove * * A 'remove' event is emitted when actions are {@link #method-remove removed} * or {@link #clear cleared}. * * @param {OO.ui.ActionWidget[]} added Actions removed */ /** * @event change * * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared}, * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed. * */ /* Methods */ /** * Handle action change events. * * @private * @fires change */ OO.ui.ActionSet.prototype.onActionChange = function () { this.organized = false; if ( this.changing ) { this.changed = true; } else { this.emit( 'change' ); } }; /** * Check if an action is one of the special actions. * * @param {OO.ui.ActionWidget} action Action to check * @return {boolean} Action is special */ OO.ui.ActionSet.prototype.isSpecial = function ( action ) { var flag; for ( flag in this.special ) { if ( action === this.special[ flag ] ) { return true; } } return false; }; /** * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’, * or ‘disabled’. * * @param {Object} [filters] Filters to use, omit to get all actions * @param {string|string[]} [filters.actions] Actions that action widgets must have * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe') * @param {string|string[]} [filters.modes] Modes that action widgets must have * @param {boolean} [filters.visible] Action widgets must be visible * @param {boolean} [filters.disabled] Action widgets must be disabled * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria */ OO.ui.ActionSet.prototype.get = function ( filters ) { var i, len, list, category, actions, index, match, matches; if ( filters ) { this.organize(); // Collect category candidates matches = []; for ( category in this.categorized ) { list = filters[ category ]; if ( list ) { if ( !Array.isArray( list ) ) { list = [ list ]; } for ( i = 0, len = list.length; i < len; i++ ) { actions = this.categorized[ category ][ list[ i ] ]; if ( Array.isArray( actions ) ) { matches.push.apply( matches, actions ); } } } } // Remove by boolean filters for ( i = 0, len = matches.length; i < len; i++ ) { match = matches[ i ]; if ( ( filters.visible !== undefined && match.isVisible() !== filters.visible ) || ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled ) ) { matches.splice( i, 1 ); len--; i--; } } // Remove duplicates for ( i = 0, len = matches.length; i < len; i++ ) { match = matches[ i ]; index = matches.lastIndexOf( match ); while ( index !== i ) { matches.splice( index, 1 ); len--; index = matches.lastIndexOf( match ); } } return matches; } return this.list.slice(); }; /** * Get 'special' actions. * * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'. * Special flags can be configured in subclasses by changing the static #specialFlags property. * * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets. */ OO.ui.ActionSet.prototype.getSpecial = function () { this.organize(); return $.extend( {}, this.special ); }; /** * Get 'other' actions. * * Other actions include all non-special visible action widgets. * * @return {OO.ui.ActionWidget[]} 'Other' action widgets */ OO.ui.ActionSet.prototype.getOthers = function () { this.organize(); return this.others.slice(); }; /** * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured * to be available in the specified mode will be made visible. All other actions will be hidden. * * @param {string} mode The mode. Only actions configured to be available in the specified * mode will be made visible. * @chainable * @fires toggle * @fires change */ OO.ui.ActionSet.prototype.setMode = function ( mode ) { var i, len, action; this.changing = true; for ( i = 0, len = this.list.length; i < len; i++ ) { action = this.list[ i ]; action.toggle( action.hasMode( mode ) ); } this.organized = false; this.changing = false; this.emit( 'change' ); return this; }; /** * Set the abilities of the specified actions. * * Action widgets that are configured with the specified actions will be enabled * or disabled based on the boolean values specified in the `actions` * parameter. * * @param {Object.<string,boolean>} actions A list keyed by action name with boolean * values that indicate whether or not the action should be enabled. * @chainable */ OO.ui.ActionSet.prototype.setAbilities = function ( actions ) { var i, len, action, item; for ( i = 0, len = this.list.length; i < len; i++ ) { item = this.list[ i ]; action = item.getAction(); if ( actions[ action ] !== undefined ) { item.setDisabled( !actions[ action ] ); } } return this; }; /** * Executes a function once per action. * * When making changes to multiple actions, use this method instead of iterating over the actions * manually to defer emitting a #change event until after all actions have been changed. * * @param {Object|null} filter Filters to use to determine which actions to iterate over; see #get * @param {Function} callback Callback to run for each action; callback is invoked with three * arguments: the action, the action's index, the list of actions being iterated over * @chainable */ OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) { this.changed = false; this.changing = true; this.get( filter ).forEach( callback ); this.changing = false; if ( this.changed ) { this.emit( 'change' ); } return this; }; /** * Add action widgets to the action set. * * @param {OO.ui.ActionWidget[]} actions Action widgets to add * @chainable * @fires add * @fires change */ OO.ui.ActionSet.prototype.add = function ( actions ) { var i, len, action; this.changing = true; for ( i = 0, len = actions.length; i < len; i++ ) { action = actions[ i ]; action.connect( this, { click: [ 'emit', 'click', action ], resize: [ 'emit', 'resize', action ], toggle: [ 'onActionChange' ] } ); this.list.push( action ); } this.organized = false; this.emit( 'add', actions ); this.changing = false; this.emit( 'change' ); return this; }; /** * Remove action widgets from the set. * * To remove all actions, you may wish to use the #clear method instead. * * @param {OO.ui.ActionWidget[]} actions Action widgets to remove * @chainable * @fires remove * @fires change */ OO.ui.ActionSet.prototype.remove = function ( actions ) { var i, len, index, action; this.changing = true; for ( i = 0, len = actions.length; i < len; i++ ) { action = actions[ i ]; index = this.list.indexOf( action ); if ( index !== -1 ) { action.disconnect( this ); this.list.splice( index, 1 ); } } this.organized = false; this.emit( 'remove', actions ); this.changing = false; this.emit( 'change' ); return this; }; /** * Remove all action widets from the set. * * To remove only specified actions, use the {@link #method-remove remove} method instead. * * @chainable * @fires remove * @fires change */ OO.ui.ActionSet.prototype.clear = function () { var i, len, action, removed = this.list.slice(); this.changing = true; for ( i = 0, len = this.list.length; i < len; i++ ) { action = this.list[ i ]; action.disconnect( this ); } this.list = []; this.organized = false; this.emit( 'remove', removed ); this.changing = false; this.emit( 'change' ); return this; }; /** * Organize actions. * * This is called whenever organized information is requested. It will only reorganize the actions * if something has changed since the last time it ran. * * @private * @chainable */ OO.ui.ActionSet.prototype.organize = function () { var i, iLen, j, jLen, flag, action, category, list, item, special, specialFlags = this.constructor.static.specialFlags; if ( !this.organized ) { this.categorized = {}; this.special = {}; this.others = []; for ( i = 0, iLen = this.list.length; i < iLen; i++ ) { action = this.list[ i ]; if ( action.isVisible() ) { // Populate categories for ( category in this.categories ) { if ( !this.categorized[ category ] ) { this.categorized[ category ] = {}; } list = action[ this.categories[ category ] ](); if ( !Array.isArray( list ) ) { list = [ list ]; } for ( j = 0, jLen = list.length; j < jLen; j++ ) { item = list[ j ]; if ( !this.categorized[ category ][ item ] ) { this.categorized[ category ][ item ] = []; } this.categorized[ category ][ item ].push( action ); } } // Populate special/others special = false; for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) { flag = specialFlags[ j ]; if ( !this.special[ flag ] && action.hasFlag( flag ) ) { this.special[ flag ] = action; special = true; break; } } if ( !special ) { this.others.push( action ); } } } this.organized = true; } return this; }; /** * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the * appearance and functionality of the error interface. * * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget * that initiated the failed process will be disabled. * * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the * process again. * * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors * * @class * * @constructor * @param {string|jQuery} message Description of error * @param {Object} [config] Configuration options * @cfg {boolean} [recoverable=true] Error is recoverable. * By default, errors are recoverable, and users can try the process again. * @cfg {boolean} [warning=false] Error is a warning. * If the error is a warning, the error interface will include a * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning * is not triggered a second time if the user chooses to continue. */ OO.ui.Error = function OoUiError( message, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( message ) && config === undefined ) { config = message; message = config.message; } // Configuration initialization config = config || {}; // Properties this.message = message instanceof jQuery ? message : String( message ); this.recoverable = config.recoverable === undefined || !!config.recoverable; this.warning = !!config.warning; }; /* Setup */ OO.initClass( OO.ui.Error ); /* Methods */ /** * Check if the error is recoverable. * * If the error is recoverable, users are able to try the process again. * * @return {boolean} Error is recoverable */ OO.ui.Error.prototype.isRecoverable = function () { return this.recoverable; }; /** * Check if the error is a warning. * * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button. * * @return {boolean} Error is warning */ OO.ui.Error.prototype.isWarning = function () { return this.warning; }; /** * Get error message as DOM nodes. * * @return {jQuery} Error message in DOM nodes */ OO.ui.Error.prototype.getMessage = function () { return this.message instanceof jQuery ? this.message.clone() : $( '<div>' ).text( this.message ).contents(); }; /** * Get the error message text. * * @return {string} Error message */ OO.ui.Error.prototype.getMessageText = function () { return this.message instanceof jQuery ? this.message.text() : this.message; }; /** * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise, * or a function: * * - **number**: the process will wait for the specified number of milliseconds before proceeding. * - **promise**: the process will continue to the next step when the promise is successfully resolved * or stop if the promise is rejected. * - **function**: the process will execute the function. The process will stop if the function returns * either a boolean `false` or a promise that is rejected; if the function returns a number, the process * will wait for that number of milliseconds before proceeding. * * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is * configured, users can dismiss the error and try the process again, or not. If a process is stopped, * its remaining steps will not be performed. * * @class * * @constructor * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is * a number or promise. */ OO.ui.Process = function ( step, context ) { // Properties this.steps = []; // Initialization if ( step !== undefined ) { this.next( step, context ); } }; /* Setup */ OO.initClass( OO.ui.Process ); /* Methods */ /** * Start the process. * * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed. * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected * and any remaining steps are not performed. */ OO.ui.Process.prototype.execute = function () { var i, len, promise; /** * Continue execution. * * @ignore * @param {Array} step A function and the context it should be called in * @return {Function} Function that continues the process */ function proceed( step ) { return function () { // Execute step in the correct context var deferred, result = step.callback.call( step.context ); if ( result === false ) { // Use rejected promise for boolean false results return $.Deferred().reject( [] ).promise(); } if ( typeof result === 'number' ) { if ( result < 0 ) { throw new Error( 'Cannot go back in time: flux capacitor is out of service' ); } // Use a delayed promise for numbers, expecting them to be in milliseconds deferred = $.Deferred(); setTimeout( deferred.resolve, result ); return deferred.promise(); } if ( result instanceof OO.ui.Error ) { // Use rejected promise for error return $.Deferred().reject( [ result ] ).promise(); } if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) { // Use rejected promise for list of errors return $.Deferred().reject( result ).promise(); } // Duck-type the object to see if it can produce a promise if ( result && $.isFunction( result.promise ) ) { // Use a promise generated from the result return result.promise(); } // Use resolved promise for other results return $.Deferred().resolve().promise(); }; } if ( this.steps.length ) { // Generate a chain reaction of promises promise = proceed( this.steps[ 0 ] )(); for ( i = 1, len = this.steps.length; i < len; i++ ) { promise = promise.then( proceed( this.steps[ i ] ) ); } } else { promise = $.Deferred().resolve().promise(); } return promise; }; /** * Create a process step. * * @private * @param {number|jQuery.Promise|Function} step * * - Number of milliseconds to wait before proceeding * - Promise that must be resolved before proceeding * - Function to execute * - If the function returns a boolean false the process will stop * - If the function returns a promise, the process will continue to the next * step when the promise is resolved or stop if the promise is rejected * - If the function returns a number, the process will wait for that number of * milliseconds before proceeding * @param {Object} [context=null] Execution context of the function. The context is * ignored if the step is a number or promise. * @return {Object} Step object, with `callback` and `context` properties */ OO.ui.Process.prototype.createStep = function ( step, context ) { if ( typeof step === 'number' || $.isFunction( step.promise ) ) { return { callback: function () { return step; }, context: null }; } if ( $.isFunction( step ) ) { return { callback: step, context: context }; } throw new Error( 'Cannot create process step: number, promise or function expected' ); }; /** * Add step to the beginning of the process. * * @inheritdoc #createStep * @return {OO.ui.Process} this * @chainable */ OO.ui.Process.prototype.first = function ( step, context ) { this.steps.unshift( this.createStep( step, context ) ); return this; }; /** * Add step to the end of the process. * * @inheritdoc #createStep * @return {OO.ui.Process} this * @chainable */ OO.ui.Process.prototype.next = function ( step, context ) { this.steps.push( this.createStep( step, context ) ); return this; }; /** * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation. * Managed windows are mutually exclusive. If a new window is opened while a current window is opening * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows * themselves are persistent and—rather than being torn down when closed—can be repopulated with the * pertinent data and reused. * * Over the lifecycle of a window, the window manager makes available three promises: `opening`, * `opened`, and `closing`, which represent the primary stages of the cycle: * * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window. * * - an `opening` event is emitted with an `opening` promise * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the * window and its result executed * - a `setup` progress notification is emitted from the `opening` promise * - the #getReadyDelay method is called the returned value is used to time a pause in execution before * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the * window and its result executed * - a `ready` progress notification is emitted from the `opening` promise * - the `opening` promise is resolved with an `opened` promise * * **Opened**: the window is now open. * * **Closing**: the closing stage begins when the window manager's #closeWindow or the * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins * to close the window. * * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the * window and its result executed * - a `hold` progress notification is emitted from the `closing` promise * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the * window and its result executed * - a `teardown` progress notification is emitted from the `closing` promise * - the `closing` promise is resolved. The window is now closed * * See the [OOjs UI documentation on MediaWiki][1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers * * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation * Note that window classes that are instantiated with a factory must have * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name. * @cfg {boolean} [modal=true] Prevent interaction outside the dialog */ OO.ui.WindowManager = function OoUiWindowManager( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.WindowManager.parent.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.factory = config.factory; this.modal = config.modal === undefined || !!config.modal; this.windows = {}; this.opening = null; this.opened = null; this.closing = null; this.preparingToOpen = null; this.preparingToClose = null; this.currentWindow = null; this.globalEvents = false; this.$returnFocusTo = null; this.$ariaHidden = null; this.onWindowResizeTimeout = null; this.onWindowResizeHandler = this.onWindowResize.bind( this ); this.afterWindowResizeHandler = this.afterWindowResize.bind( this ); // Initialization this.$element .addClass( 'oo-ui-windowManager' ) .toggleClass( 'oo-ui-windowManager-modal', this.modal ); }; /* Setup */ OO.inheritClass( OO.ui.WindowManager, OO.ui.Element ); OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter ); /* Events */ /** * An 'opening' event is emitted when the window begins to be opened. * * @event opening * @param {OO.ui.Window} win Window that's being opened * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully. * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete. * @param {Object} data Window opening data */ /** * A 'closing' event is emitted when the window begins to be closed. * * @event closing * @param {OO.ui.Window} win Window that's being closed * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window * is closed successfully. The promise emits `hold` and `teardown` notifications when those * processes are complete. When the `closing` promise is resolved, the first argument of its value * is the closing data. * @param {Object} data Window closing data */ /** * A 'resize' event is emitted when a window is resized. * * @event resize * @param {OO.ui.Window} win Window that was resized */ /* Static Properties */ /** * Map of the symbolic name of each window size and its CSS properties. * * @static * @inheritable * @property {Object} */ OO.ui.WindowManager.static.sizes = { small: { width: 300 }, medium: { width: 500 }, large: { width: 700 }, larger: { width: 900 }, full: { // These can be non-numeric because they are never used in calculations width: '100%', height: '100%' } }; /** * Symbolic name of the default window size. * * The default size is used if the window's requested size is not recognized. * * @static * @inheritable * @property {string} */ OO.ui.WindowManager.static.defaultSize = 'medium'; /* Methods */ /** * Handle window resize events. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.WindowManager.prototype.onWindowResize = function () { clearTimeout( this.onWindowResizeTimeout ); this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 ); }; /** * Handle window resize events. * * @private * @param {jQuery.Event} e Window resize event */ OO.ui.WindowManager.prototype.afterWindowResize = function () { if ( this.currentWindow ) { this.updateWindowSize( this.currentWindow ); } }; /** * Check if window is opening. * * @param {OO.ui.Window} win Window to check * @return {boolean} Window is opening */ OO.ui.WindowManager.prototype.isOpening = function ( win ) { return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending'; }; /** * Check if window is closing. * * @param {OO.ui.Window} win Window to check * @return {boolean} Window is closing */ OO.ui.WindowManager.prototype.isClosing = function ( win ) { return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending'; }; /** * Check if window is opened. * * @param {OO.ui.Window} win Window to check * @return {boolean} Window is opened */ OO.ui.WindowManager.prototype.isOpened = function ( win ) { return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending'; }; /** * Check if a window is being managed. * * @param {OO.ui.Window} win Window to check * @return {boolean} Window is being managed */ OO.ui.WindowManager.prototype.hasWindow = function ( win ) { var name; for ( name in this.windows ) { if ( this.windows[ name ] === win ) { return true; } } return false; }; /** * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process. * * @param {OO.ui.Window} win Window being opened * @param {Object} [data] Window opening data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getSetupDelay = function () { return 0; }; /** * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process. * * @param {OO.ui.Window} win Window being opened * @param {Object} [data] Window opening data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getReadyDelay = function () { return 0; }; /** * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process. * * @param {OO.ui.Window} win Window being closed * @param {Object} [data] Window closing data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getHoldDelay = function () { return 0; }; /** * Get the number of milliseconds to wait after the ‘hold’ process has finished before * executing the ‘teardown’ process. * * @param {OO.ui.Window} win Window being closed * @param {Object} [data] Window closing data * @return {number} Milliseconds to wait */ OO.ui.WindowManager.prototype.getTeardownDelay = function () { return this.modal ? 250 : 0; }; /** * Get a window by its symbolic name. * * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3] * for more information about using factories. * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers * * @param {string} name Symbolic name of the window * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory. * @throws {Error} An error is thrown if the named window is not recognized as a managed window. */ OO.ui.WindowManager.prototype.getWindow = function ( name ) { var deferred = $.Deferred(), win = this.windows[ name ]; if ( !( win instanceof OO.ui.Window ) ) { if ( this.factory ) { if ( !this.factory.lookup( name ) ) { deferred.reject( new OO.ui.Error( 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory' ) ); } else { win = this.factory.create( name ); this.addWindows( [ win ] ); deferred.resolve( win ); } } else { deferred.reject( new OO.ui.Error( 'Cannot get unmanaged window: symbolic name unrecognized as a managed window' ) ); } } else { deferred.resolve( win ); } return deferred.promise(); }; /** * Get current window. * * @return {OO.ui.Window|null} Currently opening/opened/closing window */ OO.ui.WindowManager.prototype.getCurrentWindow = function () { return this.currentWindow; }; /** * Open a window. * * @param {OO.ui.Window|string} win Window object or symbolic name of window to open * @param {Object} [data] Window opening data * @param {jQuery|null} [data.$returnFocusTo] Element to which the window will return focus when closed. * Defaults the current activeElement. If set to null, focus isn't changed on close. * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening. * See {@link #event-opening 'opening' event} for more information about `opening` promises. * @fires opening */ OO.ui.WindowManager.prototype.openWindow = function ( win, data ) { var manager = this, opening = $.Deferred(); data = data || {}; // Argument handling if ( typeof win === 'string' ) { return this.getWindow( win ).then( function ( win ) { return manager.openWindow( win, data ); } ); } // Error handling if ( !this.hasWindow( win ) ) { opening.reject( new OO.ui.Error( 'Cannot open window: window is not attached to manager' ) ); } else if ( this.preparingToOpen || this.opening || this.opened ) { opening.reject( new OO.ui.Error( 'Cannot open window: another window is opening or open' ) ); } // Window opening if ( opening.state() !== 'rejected' ) { // If a window is currently closing, wait for it to complete this.preparingToOpen = $.when( this.closing ); // Ensure handlers get called after preparingToOpen is set this.preparingToOpen.done( function () { if ( manager.modal ) { manager.toggleGlobalEvents( true ); manager.toggleAriaIsolation( true ); } manager.$returnFocusTo = data.$returnFocusTo || $( document.activeElement ); manager.currentWindow = win; manager.opening = opening; manager.preparingToOpen = null; manager.emit( 'opening', win, opening, data ); setTimeout( function () { win.setup( data ).then( function () { manager.updateWindowSize( win ); manager.opening.notify( { state: 'setup' } ); setTimeout( function () { win.ready( data ).then( function () { manager.opening.notify( { state: 'ready' } ); manager.opening = null; manager.opened = $.Deferred(); opening.resolve( manager.opened.promise(), data ); }, function () { manager.opening = null; manager.opened = $.Deferred(); opening.reject(); manager.closeWindow( win ); } ); }, manager.getReadyDelay() ); }, function () { manager.opening = null; manager.opened = $.Deferred(); opening.reject(); manager.closeWindow( win ); } ); }, manager.getSetupDelay() ); } ); } return opening.promise(); }; /** * Close a window. * * @param {OO.ui.Window|string} win Window object or symbolic name of window to close * @param {Object} [data] Window closing data * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing. * See {@link #event-closing 'closing' event} for more information about closing promises. * @throws {Error} An error is thrown if the window is not managed by the window manager. * @fires closing */ OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) { var manager = this, closing = $.Deferred(), opened; // Argument handling if ( typeof win === 'string' ) { win = this.windows[ win ]; } else if ( !this.hasWindow( win ) ) { win = null; } // Error handling if ( !win ) { closing.reject( new OO.ui.Error( 'Cannot close window: window is not attached to manager' ) ); } else if ( win !== this.currentWindow ) { closing.reject( new OO.ui.Error( 'Cannot close window: window already closed with different data' ) ); } else if ( this.preparingToClose || this.closing ) { closing.reject( new OO.ui.Error( 'Cannot close window: window already closing with different data' ) ); } // Window closing if ( closing.state() !== 'rejected' ) { // If the window is currently opening, close it when it's done this.preparingToClose = $.when( this.opening ); // Ensure handlers get called after preparingToClose is set this.preparingToClose.always( function () { manager.closing = closing; manager.preparingToClose = null; manager.emit( 'closing', win, closing, data ); opened = manager.opened; manager.opened = null; opened.resolve( closing.promise(), data ); setTimeout( function () { win.hold( data ).then( function () { closing.notify( { state: 'hold' } ); setTimeout( function () { win.teardown( data ).then( function () { closing.notify( { state: 'teardown' } ); if ( manager.modal ) { manager.toggleGlobalEvents( false ); manager.toggleAriaIsolation( false ); } if ( manager.$returnFocusTo && manager.$returnFocusTo.length ) { manager.$returnFocusTo[ 0 ].focus(); } manager.closing = null; manager.currentWindow = null; closing.resolve( data ); } ); }, manager.getTeardownDelay() ); } ); }, manager.getHoldDelay() ); } ); } return closing.promise(); }; /** * Add windows to the window manager. * * Windows can be added by reference, symbolic name, or explicitly defined symbolic names. * See the [OOjs ui documentation on MediaWiki] [2] for examples. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers * * This function can be called in two manners: * * 1. `.addWindows( [ windowA, windowB, ... ] )` (where `windowA`, `windowB` are OO.ui.Window objects) * * This syntax registers windows under the symbolic names defined in their `.static.name` * properties. For example, if `windowA.constructor.static.name` is `'nameA'`, calling * `.openWindow( 'nameA' )` afterwards will open the window `windowA`. This syntax requires the * static name to be set, otherwise an exception will be thrown. * * This is the recommended way, as it allows for an easier switch to using a window factory. * * 2. `.addWindows( { nameA: windowA, nameB: windowB, ... } )` * * This syntax registers windows under the explicitly given symbolic names. In this example, * calling `.openWindow( 'nameA' )` afterwards will open the window `windowA`, regardless of what * its `.static.name` is set to. The static name is not required to be set. * * This should only be used if you need to override the default symbolic names. * * Example: * * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * * // Add a window under the default name: see OO.ui.MessageDialog.static.name * windowManager.addWindows( [ new OO.ui.MessageDialog() ] ); * // Add a window under an explicit name * windowManager.addWindows( { myMessageDialog: new OO.ui.MessageDialog() } ); * * // Open window by default name * windowManager.openWindow( 'message' ); * // Open window by explicitly given name * windowManager.openWindow( 'myMessageDialog' ); * * * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified * by reference, symbolic name, or explicitly defined symbolic names. * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an * explicit nor a statically configured symbolic name. */ OO.ui.WindowManager.prototype.addWindows = function ( windows ) { var i, len, win, name, list; if ( Array.isArray( windows ) ) { // Convert to map of windows by looking up symbolic names from static configuration list = {}; for ( i = 0, len = windows.length; i < len; i++ ) { name = windows[ i ].constructor.static.name; if ( !name ) { throw new Error( 'Windows must have a `name` static property defined.' ); } list[ name ] = windows[ i ]; } } else if ( OO.isPlainObject( windows ) ) { list = windows; } // Add windows for ( name in list ) { win = list[ name ]; this.windows[ name ] = win.toggle( false ); this.$element.append( win.$element ); win.setManager( this ); } }; /** * Remove the specified windows from the windows manager. * * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no * longer listens to events, use the #destroy method. * * @param {string[]} names Symbolic names of windows to remove * @return {jQuery.Promise} Promise resolved when window is closed and removed * @throws {Error} An error is thrown if the named windows are not managed by the window manager. */ OO.ui.WindowManager.prototype.removeWindows = function ( names ) { var i, len, win, name, cleanupWindow, manager = this, promises = [], cleanup = function ( name, win ) { delete manager.windows[ name ]; win.$element.detach(); }; for ( i = 0, len = names.length; i < len; i++ ) { name = names[ i ]; win = this.windows[ name ]; if ( !win ) { throw new Error( 'Cannot remove window' ); } cleanupWindow = cleanup.bind( null, name, win ); promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) ); } return $.when.apply( $, promises ); }; /** * Remove all windows from the window manager. * * Windows will be closed before they are removed. Note that the window manager, though not in use, will still * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead. * To remove just a subset of windows, use the #removeWindows method. * * @return {jQuery.Promise} Promise resolved when all windows are closed and removed */ OO.ui.WindowManager.prototype.clearWindows = function () { return this.removeWindows( Object.keys( this.windows ) ); }; /** * Set dialog size. In general, this method should not be called directly. * * Fullscreen mode will be used if the dialog is too wide to fit in the screen. * * @param {OO.ui.Window} win Window to update, should be the current window * @chainable */ OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) { var isFullscreen; // Bypass for non-current, and thus invisible, windows if ( win !== this.currentWindow ) { return; } isFullscreen = win.getSize() === 'full'; this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen ); this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen ); win.setDimensions( win.getSizeProperties() ); this.emit( 'resize', win ); return this; }; /** * Bind or unbind global events for scrolling. * * @private * @param {boolean} [on] Bind global events * @chainable */ OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) { var scrollWidth, bodyMargin, $body = $( this.getElementDocument().body ), // We could have multiple window managers open so only modify // the body css at the bottom of the stack stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0; on = on === undefined ? !!this.globalEvents : !!on; if ( on ) { if ( !this.globalEvents ) { $( this.getElementWindow() ).on( { // Start listening for top-level window dimension changes 'orientationchange resize': this.onWindowResizeHandler } ); if ( stackDepth === 0 ) { scrollWidth = window.innerWidth - document.documentElement.clientWidth; bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0; $body.css( { overflow: 'hidden', 'margin-right': bodyMargin + scrollWidth } ); } stackDepth++; this.globalEvents = true; } } else if ( this.globalEvents ) { $( this.getElementWindow() ).off( { // Stop listening for top-level window dimension changes 'orientationchange resize': this.onWindowResizeHandler } ); stackDepth--; if ( stackDepth === 0 ) { $body.css( { overflow: '', 'margin-right': '' } ); } this.globalEvents = false; } $body.data( 'windowManagerGlobalEvents', stackDepth ); return this; }; /** * Toggle screen reader visibility of content other than the window manager. * * @private * @param {boolean} [isolate] Make only the window manager visible to screen readers * @chainable */ OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) { isolate = isolate === undefined ? !this.$ariaHidden : !!isolate; if ( isolate ) { if ( !this.$ariaHidden ) { // Hide everything other than the window manager from screen readers this.$ariaHidden = $( 'body' ) .children() .not( this.$element.parentsUntil( 'body' ).last() ) .attr( 'aria-hidden', '' ); } } else if ( this.$ariaHidden ) { // Restore screen reader visibility this.$ariaHidden.removeAttr( 'aria-hidden' ); this.$ariaHidden = null; } return this; }; /** * Destroy the window manager. * * Destroying the window manager ensures that it will no longer listen to events. If you would like to * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method * instead. */ OO.ui.WindowManager.prototype.destroy = function () { this.toggleGlobalEvents( false ); this.toggleAriaIsolation( false ); this.clearWindows(); this.$element.remove(); }; /** * A window is a container for elements that are in a child frame. They are used with * a window manager (OO.ui.WindowManager), which is used to open and close the window and control * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’, * ‘large’), which is interpreted by the window manager. If the requested size is not recognized, * the window manager will choose a sensible fallback. * * The lifecycle of a window has three primary stages (opening, opened, and closing) in which * different processes are executed: * * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open * the window. * * - {@link #getSetupProcess} method is called and its result executed * - {@link #getReadyProcess} method is called and its result executed * * **opened**: The window is now open * * **closing**: The closing stage begins when the window manager's * {@link OO.ui.WindowManager#closeWindow closeWindow} * or the window's {@link #close} methods are used, and the window manager begins to close the window. * * - {@link #getHoldProcess} method is called and its result executed * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed * * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous * processing can complete. Always assume window processes are executed asynchronously. * * For more information, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows * * @abstract * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or * `full`. If omitted, the value of the {@link #static-size static size} property will be used. */ OO.ui.Window = function OoUiWindow( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.Window.parent.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.manager = null; this.size = config.size || this.constructor.static.size; this.$frame = $( '<div>' ); this.$overlay = $( '<div>' ); this.$content = $( '<div>' ); this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 ); this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 ); this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter ); // Initialization this.$overlay.addClass( 'oo-ui-window-overlay' ); this.$content .addClass( 'oo-ui-window-content' ) .attr( 'tabindex', 0 ); this.$frame .addClass( 'oo-ui-window-frame' ) .append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter ); this.$element .addClass( 'oo-ui-window' ) .append( this.$frame, this.$overlay ); // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods // that reference properties not initialized at that time of parent class construction // TODO: Find a better way to handle post-constructor setup this.visible = false; this.$element.addClass( 'oo-ui-element-hidden' ); }; /* Setup */ OO.inheritClass( OO.ui.Window, OO.ui.Element ); OO.mixinClass( OO.ui.Window, OO.EventEmitter ); /* Static Properties */ /** * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`. * * The static size is used if no #size is configured during construction. * * @static * @inheritable * @property {string} */ OO.ui.Window.static.size = 'medium'; /* Methods */ /** * Handle mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.Window.prototype.onMouseDown = function ( e ) { // Prevent clicking on the click-block from stealing focus if ( e.target === this.$element[ 0 ] ) { return false; } }; /** * Check if the window has been initialized. * * Initialization occurs when a window is added to a manager. * * @return {boolean} Window has been initialized */ OO.ui.Window.prototype.isInitialized = function () { return !!this.manager; }; /** * Check if the window is visible. * * @return {boolean} Window is visible */ OO.ui.Window.prototype.isVisible = function () { return this.visible; }; /** * Check if the window is opening. * * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening} * method. * * @return {boolean} Window is opening */ OO.ui.Window.prototype.isOpening = function () { return this.manager.isOpening( this ); }; /** * Check if the window is closing. * * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method. * * @return {boolean} Window is closing */ OO.ui.Window.prototype.isClosing = function () { return this.manager.isClosing( this ); }; /** * Check if the window is opened. * * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method. * * @return {boolean} Window is opened */ OO.ui.Window.prototype.isOpened = function () { return this.manager.isOpened( this ); }; /** * Get the window manager. * * All windows must be attached to a window manager, which is used to open * and close the window and control its presentation. * * @return {OO.ui.WindowManager} Manager of window */ OO.ui.Window.prototype.getManager = function () { return this.manager; }; /** * Get the symbolic name of the window size (e.g., `small` or `medium`). * * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full` */ OO.ui.Window.prototype.getSize = function () { var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ), sizes = this.manager.constructor.static.sizes, size = this.size; if ( !sizes[ size ] ) { size = this.manager.constructor.static.defaultSize; } if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) { size = 'full'; } return size; }; /** * Get the size properties associated with the current window size * * @return {Object} Size properties */ OO.ui.Window.prototype.getSizeProperties = function () { return this.manager.constructor.static.sizes[ this.getSize() ]; }; /** * Disable transitions on window's frame for the duration of the callback function, then enable them * back. * * @private * @param {Function} callback Function to call while transitions are disabled */ OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) { // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements. // Disable transitions first, otherwise we'll get values from when the window was animating. // We need to build the transition CSS properties using these specific properties since // Firefox doesn't return anything useful when asked just for 'transition'. var oldTransition = this.$frame.css( 'transition-property' ) + ' ' + this.$frame.css( 'transition-duration' ) + ' ' + this.$frame.css( 'transition-timing-function' ) + ' ' + this.$frame.css( 'transition-delay' ); this.$frame.css( 'transition', 'none' ); callback(); // Force reflow to make sure the style changes done inside callback // really are not transitioned this.$frame.height(); this.$frame.css( 'transition', oldTransition ); }; /** * Get the height of the full window contents (i.e., the window head, body and foot together). * * What consistitutes the head, body, and foot varies depending on the window type. * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body, * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title * and special actions in the head, and dialog content in the body. * * To get just the height of the dialog body, use the #getBodyHeight method. * * @return {number} The height of the window contents (the dialog head, body and foot) in pixels */ OO.ui.Window.prototype.getContentHeight = function () { var bodyHeight, win = this, bodyStyleObj = this.$body[ 0 ].style, frameStyleObj = this.$frame[ 0 ].style; // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements. // Disable transitions first, otherwise we'll get values from when the window was animating. this.withoutSizeTransitions( function () { var oldHeight = frameStyleObj.height, oldPosition = bodyStyleObj.position; frameStyleObj.height = '1px'; // Force body to resize to new width bodyStyleObj.position = 'relative'; bodyHeight = win.getBodyHeight(); frameStyleObj.height = oldHeight; bodyStyleObj.position = oldPosition; } ); return ( // Add buffer for border ( this.$frame.outerHeight() - this.$frame.innerHeight() ) + // Use combined heights of children ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) ) ); }; /** * Get the height of the window body. * * To get the height of the full window contents (the window body, head, and foot together), * use #getContentHeight. * * When this function is called, the window will temporarily have been resized * to height=1px, so .scrollHeight measurements can be taken accurately. * * @return {number} Height of the window body in pixels */ OO.ui.Window.prototype.getBodyHeight = function () { return this.$body[ 0 ].scrollHeight; }; /** * Get the directionality of the frame (right-to-left or left-to-right). * * @return {string} Directionality: `'ltr'` or `'rtl'` */ OO.ui.Window.prototype.getDir = function () { return OO.ui.Element.static.getDir( this.$content ) || 'ltr'; }; /** * Get the 'setup' process. * * The setup process is used to set up a window for use in a particular context, * based on the `data` argument. This method is called during the opening phase of the window’s * lifecycle. * * Override this method to add additional steps to the ‘setup’ process the parent method provides * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods * of OO.ui.Process. * * To add window content that persists between openings, you may wish to use the #initialize method * instead. * * @param {Object} [data] Window opening data * @return {OO.ui.Process} Setup process */ OO.ui.Window.prototype.getSetupProcess = function () { return new OO.ui.Process(); }; /** * Get the ‘ready’ process. * * The ready process is used to ready a window for use in a particular * context, based on the `data` argument. This method is called during the opening phase of * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}. * * Override this method to add additional steps to the ‘ready’ process the parent method * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} * methods of OO.ui.Process. * * @param {Object} [data] Window opening data * @return {OO.ui.Process} Ready process */ OO.ui.Window.prototype.getReadyProcess = function () { return new OO.ui.Process(); }; /** * Get the 'hold' process. * * The hold process is used to keep a window from being used in a particular context, * based on the `data` argument. This method is called during the closing phase of the window’s * lifecycle. * * Override this method to add additional steps to the 'hold' process the parent method provides * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods * of OO.ui.Process. * * @param {Object} [data] Window closing data * @return {OO.ui.Process} Hold process */ OO.ui.Window.prototype.getHoldProcess = function () { return new OO.ui.Process(); }; /** * Get the ‘teardown’ process. * * The teardown process is used to teardown a window after use. During teardown, * user interactions within the window are conveyed and the window is closed, based on the `data` * argument. This method is called during the closing phase of the window’s lifecycle. * * Override this method to add additional steps to the ‘teardown’ process the parent method provides * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods * of OO.ui.Process. * * @param {Object} [data] Window closing data * @return {OO.ui.Process} Teardown process */ OO.ui.Window.prototype.getTeardownProcess = function () { return new OO.ui.Process(); }; /** * Set the window manager. * * This will cause the window to initialize. Calling it more than once will cause an error. * * @param {OO.ui.WindowManager} manager Manager for this window * @throws {Error} An error is thrown if the method is called more than once * @chainable */ OO.ui.Window.prototype.setManager = function ( manager ) { if ( this.manager ) { throw new Error( 'Cannot set window manager, window already has a manager' ); } this.manager = manager; this.initialize(); return this; }; /** * Set the window size by symbolic name (e.g., 'small' or 'medium') * * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or * `full` * @chainable */ OO.ui.Window.prototype.setSize = function ( size ) { this.size = size; this.updateSize(); return this; }; /** * Update the window size. * * @throws {Error} An error is thrown if the window is not attached to a window manager * @chainable */ OO.ui.Window.prototype.updateSize = function () { if ( !this.manager ) { throw new Error( 'Cannot update window size, must be attached to a manager' ); } this.manager.updateWindowSize( this ); return this; }; /** * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager} * when the window is opening. In general, setDimensions should not be called directly. * * To set the size of the window, use the #setSize method. * * @param {Object} dim CSS dimension properties * @param {string|number} [dim.width] Width * @param {string|number} [dim.minWidth] Minimum width * @param {string|number} [dim.maxWidth] Maximum width * @param {string|number} [dim.height] Height, omit to set based on height of contents * @param {string|number} [dim.minHeight] Minimum height * @param {string|number} [dim.maxHeight] Maximum height * @chainable */ OO.ui.Window.prototype.setDimensions = function ( dim ) { var height, win = this, styleObj = this.$frame[ 0 ].style; // Calculate the height we need to set using the correct width if ( dim.height === undefined ) { this.withoutSizeTransitions( function () { var oldWidth = styleObj.width; win.$frame.css( 'width', dim.width || '' ); height = win.getContentHeight(); styleObj.width = oldWidth; } ); } else { height = dim.height; } this.$frame.css( { width: dim.width || '', minWidth: dim.minWidth || '', maxWidth: dim.maxWidth || '', height: height || '', minHeight: dim.minHeight || '', maxHeight: dim.maxHeight || '' } ); return this; }; /** * Initialize window contents. * * Before the window is opened for the first time, #initialize is called so that content that * persists between openings can be added to the window. * * To set up a window with new content each time the window opens, use #getSetupProcess. * * @throws {Error} An error is thrown if the window is not attached to a window manager * @chainable */ OO.ui.Window.prototype.initialize = function () { if ( !this.manager ) { throw new Error( 'Cannot initialize window, must be attached to a manager' ); } // Properties this.$head = $( '<div>' ); this.$body = $( '<div>' ); this.$foot = $( '<div>' ); this.$document = $( this.getElementDocument() ); // Events this.$element.on( 'mousedown', this.onMouseDown.bind( this ) ); // Initialization this.$head.addClass( 'oo-ui-window-head' ); this.$body.addClass( 'oo-ui-window-body' ); this.$foot.addClass( 'oo-ui-window-foot' ); this.$content.append( this.$head, this.$body, this.$foot ); return this; }; /** * Called when someone tries to focus the hidden element at the end of the dialog. * Sends focus back to the start of the dialog. * * @param {jQuery.Event} event Focus event */ OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) { var backwards = this.$focusTrapBefore.is( event.target ), element = OO.ui.findFocusable( this.$content, backwards ); if ( element ) { // There's a focusable element inside the content, at the front or // back depending on which focus trap we hit; select it. element.focus(); } else { // There's nothing focusable inside the content. As a fallback, // this.$content is focusable, and focusing it will keep our focus // properly trapped. It's not a *meaningful* focus, since it's just // the content-div for the Window, but it's better than letting focus // escape into the page. this.$content.focus(); } }; /** * Open the window. * * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow} * method, which returns a promise resolved when the window is done opening. * * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess. * * @param {Object} [data] Window opening data * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected * if the window fails to open. When the promise is resolved successfully, the first argument of the * value is a new promise, which is resolved when the window begins closing. * @throws {Error} An error is thrown if the window is not attached to a window manager */ OO.ui.Window.prototype.open = function ( data ) { if ( !this.manager ) { throw new Error( 'Cannot open window, must be attached to a manager' ); } return this.manager.openWindow( this, data ); }; /** * Close the window. * * This method is a wrapper around a call to the window * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method, * which returns a closing promise resolved when the window is done closing. * * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing * phase of the window’s lifecycle and can be used to specify closing behavior each time * the window closes. * * @param {Object} [data] Window closing data * @return {jQuery.Promise} Promise resolved when window is closed * @throws {Error} An error is thrown if the window is not attached to a window manager */ OO.ui.Window.prototype.close = function ( data ) { if ( !this.manager ) { throw new Error( 'Cannot close window, must be attached to a manager' ); } return this.manager.closeWindow( this, data ); }; /** * Setup window. * * This is called by OO.ui.WindowManager during window opening, and should not be called directly * by other systems. * * @param {Object} [data] Window opening data * @return {jQuery.Promise} Promise resolved when window is setup */ OO.ui.Window.prototype.setup = function ( data ) { var win = this; this.toggle( true ); this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this ); this.$focusTraps.on( 'focus', this.focusTrapHandler ); return this.getSetupProcess( data ).execute().then( function () { // Force redraw by asking the browser to measure the elements' widths win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width(); win.$content.addClass( 'oo-ui-window-content-setup' ).width(); } ); }; /** * Ready window. * * This is called by OO.ui.WindowManager during window opening, and should not be called directly * by other systems. * * @param {Object} [data] Window opening data * @return {jQuery.Promise} Promise resolved when window is ready */ OO.ui.Window.prototype.ready = function ( data ) { var win = this; this.$content.focus(); return this.getReadyProcess( data ).execute().then( function () { // Force redraw by asking the browser to measure the elements' widths win.$element.addClass( 'oo-ui-window-ready' ).width(); win.$content.addClass( 'oo-ui-window-content-ready' ).width(); } ); }; /** * Hold window. * * This is called by OO.ui.WindowManager during window closing, and should not be called directly * by other systems. * * @param {Object} [data] Window closing data * @return {jQuery.Promise} Promise resolved when window is held */ OO.ui.Window.prototype.hold = function ( data ) { var win = this; return this.getHoldProcess( data ).execute().then( function () { // Get the focused element within the window's content var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement ); // Blur the focused element if ( $focus.length ) { $focus[ 0 ].blur(); } // Force redraw by asking the browser to measure the elements' widths win.$element.removeClass( 'oo-ui-window-ready' ).width(); win.$content.removeClass( 'oo-ui-window-content-ready' ).width(); } ); }; /** * Teardown window. * * This is called by OO.ui.WindowManager during window closing, and should not be called directly * by other systems. * * @param {Object} [data] Window closing data * @return {jQuery.Promise} Promise resolved when window is torn down */ OO.ui.Window.prototype.teardown = function ( data ) { var win = this; return this.getTeardownProcess( data ).execute().then( function () { // Force redraw by asking the browser to measure the elements' widths win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width(); win.$content.removeClass( 'oo-ui-window-content-setup' ).width(); win.$focusTraps.off( 'focus', win.focusTrapHandler ); win.toggle( false ); } ); }; /** * The Dialog class serves as the base class for the other types of dialogs. * Unless extended to include controls, the rendered dialog box is a simple window * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager, * which opens, closes, and controls the presentation of the window. See the * [OOjs UI documentation on MediaWiki] [1] for more information. * * @example * // A simple dialog window. * function MyDialog( config ) { * MyDialog.parent.call( this, config ); * } * OO.inheritClass( MyDialog, OO.ui.Dialog ); * MyDialog.static.name = 'myDialog'; * MyDialog.prototype.initialize = function () { * MyDialog.parent.prototype.initialize.call( this ); * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' ); * this.$body.append( this.content.$element ); * }; * MyDialog.prototype.getBodyHeight = function () { * return this.content.$element.outerHeight( true ); * }; * var myDialog = new MyDialog( { * size: 'medium' * } ); * // Create and append a window manager, which opens and closes the window. * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * windowManager.addWindows( [ myDialog ] ); * // Open the window! * windowManager.openWindow( myDialog ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs * * @abstract * @class * @extends OO.ui.Window * @mixins OO.ui.mixin.PendingElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.Dialog = function OoUiDialog( config ) { // Parent constructor OO.ui.Dialog.parent.call( this, config ); // Mixin constructors OO.ui.mixin.PendingElement.call( this ); // Properties this.actions = new OO.ui.ActionSet(); this.attachedActions = []; this.currentAction = null; this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this ); // Events this.actions.connect( this, { click: 'onActionClick', change: 'onActionsChange' } ); // Initialization this.$element .addClass( 'oo-ui-dialog' ) .attr( 'role', 'dialog' ); }; /* Setup */ OO.inheritClass( OO.ui.Dialog, OO.ui.Window ); OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement ); /* Static Properties */ /** * Symbolic name of dialog. * * The dialog class must have a symbolic name in order to be registered with OO.Factory. * Please see the [OOjs UI documentation on MediaWiki] [3] for more information. * * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers * * @abstract * @static * @inheritable * @property {string} */ OO.ui.Dialog.static.name = ''; /** * The dialog title. * * The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function * that will produce a Label node or string. The title can also be specified with data passed to the * constructor (see #getSetupProcess). In this case, the static value will be overridden. * * @abstract * @static * @inheritable * @property {jQuery|string|Function} */ OO.ui.Dialog.static.title = ''; /** * An array of configured {@link OO.ui.ActionWidget action widgets}. * * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static * value will be overridden. * * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets * * @static * @inheritable * @property {Object[]} */ OO.ui.Dialog.static.actions = []; /** * Close the dialog when the 'Esc' key is pressed. * * @static * @abstract * @inheritable * @property {boolean} */ OO.ui.Dialog.static.escapable = true; /* Methods */ /** * Handle frame document key down events. * * @private * @param {jQuery.Event} e Key down event */ OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) { var actions; if ( e.which === OO.ui.Keys.ESCAPE && this.constructor.static.escapable ) { this.executeAction( '' ); e.preventDefault(); e.stopPropagation(); } else if ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) { actions = this.actions.get( { flags: 'primary', visible: true, disabled: false } ); if ( actions.length > 0 ) { this.executeAction( actions[ 0 ].getAction() ); e.preventDefault(); e.stopPropagation(); } } }; /** * Handle action click events. * * @private * @param {OO.ui.ActionWidget} action Action that was clicked */ OO.ui.Dialog.prototype.onActionClick = function ( action ) { if ( !this.isPending() ) { this.executeAction( action.getAction() ); } }; /** * Handle actions change event. * * @private */ OO.ui.Dialog.prototype.onActionsChange = function () { this.detachActions(); if ( !this.isClosing() ) { this.attachActions(); } }; /** * Get the set of actions used by the dialog. * * @return {OO.ui.ActionSet} */ OO.ui.Dialog.prototype.getActions = function () { return this.actions; }; /** * Get a process for taking action. * * When you override this method, you can create a new OO.ui.Process and return it, or add additional * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'} * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process. * * @param {string} [action] Symbolic name of action * @return {OO.ui.Process} Action process */ OO.ui.Dialog.prototype.getActionProcess = function ( action ) { return new OO.ui.Process() .next( function () { if ( !action ) { // An empty action always closes the dialog without data, which should always be // safe and make no changes this.close(); } }, this ); }; /** * @inheritdoc * * @param {Object} [data] Dialog opening data * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use * the {@link #static-title static title} * @param {Object[]} [data.actions] List of configuration options for each * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}. */ OO.ui.Dialog.prototype.getSetupProcess = function ( data ) { data = data || {}; // Parent method return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data ) .next( function () { var config = this.constructor.static, actions = data.actions !== undefined ? data.actions : config.actions, title = data.title !== undefined ? data.title : config.title; this.title.setLabel( title ).setTitle( title ); this.actions.add( this.getActionWidgets( actions ) ); this.$element.on( 'keydown', this.onDialogKeyDownHandler ); }, this ); }; /** * @inheritdoc */ OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) { // Parent method return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data ) .first( function () { this.$element.off( 'keydown', this.onDialogKeyDownHandler ); this.actions.clear(); this.currentAction = null; }, this ); }; /** * @inheritdoc */ OO.ui.Dialog.prototype.initialize = function () { var titleId; // Parent method OO.ui.Dialog.parent.prototype.initialize.call( this ); titleId = OO.ui.generateElementId(); // Properties this.title = new OO.ui.LabelWidget( { id: titleId } ); // Initialization this.$content.addClass( 'oo-ui-dialog-content' ); this.$element.attr( 'aria-labelledby', titleId ); this.setPendingElement( this.$head ); }; /** * Get action widgets from a list of configs * * @param {Object[]} actions Action widget configs * @return {OO.ui.ActionWidget[]} Action widgets */ OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) { var i, len, widgets = []; for ( i = 0, len = actions.length; i < len; i++ ) { widgets.push( new OO.ui.ActionWidget( actions[ i ] ) ); } return widgets; }; /** * Attach action actions. * * @protected */ OO.ui.Dialog.prototype.attachActions = function () { // Remember the list of potentially attached actions this.attachedActions = this.actions.get(); }; /** * Detach action actions. * * @protected * @chainable */ OO.ui.Dialog.prototype.detachActions = function () { var i, len; // Detach all actions that may have been previously attached for ( i = 0, len = this.attachedActions.length; i < len; i++ ) { this.attachedActions[ i ].$element.detach(); } this.attachedActions = []; }; /** * Execute an action. * * @param {string} action Symbolic name of action to execute * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails */ OO.ui.Dialog.prototype.executeAction = function ( action ) { this.pushPending(); this.currentAction = action; return this.getActionProcess( action ).execute() .always( this.popPending.bind( this ) ); }; /** * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box * consists of a header that contains the dialog title, a body with the message, and a footer that * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type * of {@link OO.ui.Dialog dialog} that is usually instantiated directly. * * There are two basic types of message dialogs, confirmation and alert: * * - **confirmation**: the dialog title describes what a progressive action will do and the message provides * more details about the consequences. * - **alert**: the dialog title describes which event occurred and the message provides more information * about why the event occurred. * * The MessageDialog class specifies two actions: ‘accept’, the primary * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window, * passing along the selected action. * * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example: Creating and opening a message dialog window. * var messageDialog = new OO.ui.MessageDialog(); * * // Create and append a window manager. * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * windowManager.addWindows( [ messageDialog ] ); * // Open the window. * windowManager.openWindow( messageDialog, { * title: 'Basic message dialog', * message: 'This is the message' * } ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs * * @class * @extends OO.ui.Dialog * * @constructor * @param {Object} [config] Configuration options */ OO.ui.MessageDialog = function OoUiMessageDialog( config ) { // Parent constructor OO.ui.MessageDialog.parent.call( this, config ); // Properties this.verticalActionLayout = null; // Initialization this.$element.addClass( 'oo-ui-messageDialog' ); }; /* Setup */ OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog ); /* Static Properties */ /** * @static * @inheritdoc */ OO.ui.MessageDialog.static.name = 'message'; /** * @static * @inheritdoc */ OO.ui.MessageDialog.static.size = 'small'; /** * @static * @deprecated since v0.18.4 as default; TODO: Remove */ OO.ui.MessageDialog.static.verbose = true; /** * Dialog title. * * The title of a confirmation dialog describes what a progressive action will do. The * title of an alert dialog describes which event occurred. * * @static * @inheritable * @property {jQuery|string|Function|null} */ OO.ui.MessageDialog.static.title = null; /** * The message displayed in the dialog body. * * A confirmation message describes the consequences of a progressive action. An alert * message describes why an event occurred. * * @static * @inheritable * @property {jQuery|string|Function|null} */ OO.ui.MessageDialog.static.message = null; /** * @static * @inheritdoc */ OO.ui.MessageDialog.static.actions = [ // Note that OO.ui.alert() and OO.ui.confirm() rely on these. { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' }, { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' } ]; /* Methods */ /** * @inheritdoc */ OO.ui.MessageDialog.prototype.setManager = function ( manager ) { OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager ); // Events this.manager.connect( this, { resize: 'onResize' } ); return this; }; /** * Handle window resized events. * * @private */ OO.ui.MessageDialog.prototype.onResize = function () { var dialog = this; dialog.fitActions(); // Wait for CSS transition to finish and do it again :( setTimeout( function () { dialog.fitActions(); }, 300 ); }; /** * Toggle action layout between vertical and horizontal. * * @private * @param {boolean} [value] Layout actions vertically, omit to toggle * @chainable */ OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) { value = value === undefined ? !this.verticalActionLayout : !!value; if ( value !== this.verticalActionLayout ) { this.verticalActionLayout = value; this.$actions .toggleClass( 'oo-ui-messageDialog-actions-vertical', value ) .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value ); } return this; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) { if ( action ) { return new OO.ui.Process( function () { this.close( { action: action } ); }, this ); } return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action ); }; /** * @inheritdoc * * @param {Object} [data] Dialog opening data * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each * action item */ OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) { data = data || {}; // Parent method return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data ) .next( function () { this.title.setLabel( data.title !== undefined ? data.title : this.constructor.static.title ); this.message.setLabel( data.message !== undefined ? data.message : this.constructor.static.message ); // @deprecated since v0.18.4 as default; TODO: Remove and make default instead. this.message.$element.toggleClass( 'oo-ui-messageDialog-message-verbose', data.verbose !== undefined ? data.verbose : this.constructor.static.verbose ); }, this ); }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) { data = data || {}; // Parent method return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data ) .next( function () { // Focus the primary action button var actions = this.actions.get(); actions = actions.filter( function ( action ) { return action.getFlags().indexOf( 'primary' ) > -1; } ); if ( actions.length > 0 ) { actions[ 0 ].$button.focus(); } }, this ); }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.getBodyHeight = function () { var bodyHeight, oldOverflow, $scrollable = this.container.$element; oldOverflow = $scrollable[ 0 ].style.overflow; $scrollable[ 0 ].style.overflow = 'hidden'; OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] ); bodyHeight = this.text.$element.outerHeight( true ); $scrollable[ 0 ].style.overflow = oldOverflow; return bodyHeight; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) { var $scrollable = this.container.$element; OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim ); // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced. // Need to do it after transition completes (250ms), add 50ms just in case. setTimeout( function () { var oldOverflow = $scrollable[ 0 ].style.overflow, activeElement = document.activeElement; $scrollable[ 0 ].style.overflow = 'hidden'; OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] ); // Check reconsiderScrollbars didn't destroy our focus, as we // are doing this after the ready process. if ( activeElement && activeElement !== document.activeElement && activeElement.focus ) { activeElement.focus(); } $scrollable[ 0 ].style.overflow = oldOverflow; }, 300 ); return this; }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.initialize = function () { // Parent method OO.ui.MessageDialog.parent.prototype.initialize.call( this ); // Properties this.$actions = $( '<div>' ); this.container = new OO.ui.PanelLayout( { scrollable: true, classes: [ 'oo-ui-messageDialog-container' ] } ); this.text = new OO.ui.PanelLayout( { padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ] } ); this.message = new OO.ui.LabelWidget( { classes: [ 'oo-ui-messageDialog-message' ] } ); // Initialization this.title.$element.addClass( 'oo-ui-messageDialog-title' ); this.$content.addClass( 'oo-ui-messageDialog-content' ); this.container.$element.append( this.text.$element ); this.text.$element.append( this.title.$element, this.message.$element ); this.$body.append( this.container.$element ); this.$actions.addClass( 'oo-ui-messageDialog-actions' ); this.$foot.append( this.$actions ); }; /** * @inheritdoc */ OO.ui.MessageDialog.prototype.attachActions = function () { var i, len, other, special, others; // Parent method OO.ui.MessageDialog.parent.prototype.attachActions.call( this ); special = this.actions.getSpecial(); others = this.actions.getOthers(); if ( special.safe ) { this.$actions.append( special.safe.$element ); special.safe.toggleFramed( false ); } if ( others.length ) { for ( i = 0, len = others.length; i < len; i++ ) { other = others[ i ]; this.$actions.append( other.$element ); other.toggleFramed( false ); } } if ( special.primary ) { this.$actions.append( special.primary.$element ); special.primary.toggleFramed( false ); } if ( !this.isOpening() ) { // If the dialog is currently opening, this will be called automatically soon. // This also calls #fitActions. this.updateSize(); } }; /** * Fit action actions into columns or rows. * * Columns will be used if all labels can fit without overflow, otherwise rows will be used. * * @private */ OO.ui.MessageDialog.prototype.fitActions = function () { var i, len, action, previous = this.verticalActionLayout, actions = this.actions.get(); // Detect clipping this.toggleVerticalActionLayout( false ); for ( i = 0, len = actions.length; i < len; i++ ) { action = actions[ i ]; if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) { this.toggleVerticalActionLayout( true ); break; } } // Move the body out of the way of the foot this.$body.css( 'bottom', this.$foot.outerHeight( true ) ); if ( this.verticalActionLayout !== previous ) { // We changed the layout, window height might need to be updated. this.updateSize(); } }; /** * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when * relevant. The ProcessDialog class is always extended and customized with the actions and content * required for each process. * * The process dialog box consists of a header that visually represents the ‘working’ state of long * processes with an animation. The header contains the dialog title as well as * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and * a ‘primary’ action on the right (e.g., ‘Done’). * * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}. * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples. * * @example * // Example: Creating and opening a process dialog window. * function MyProcessDialog( config ) { * MyProcessDialog.parent.call( this, config ); * } * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog ); * * MyProcessDialog.static.name = 'myProcessDialog'; * MyProcessDialog.static.title = 'Process dialog'; * MyProcessDialog.static.actions = [ * { action: 'save', label: 'Done', flags: 'primary' }, * { label: 'Cancel', flags: 'safe' } * ]; * * MyProcessDialog.prototype.initialize = function () { * MyProcessDialog.parent.prototype.initialize.apply( this, arguments ); * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } ); * this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' ); * this.$body.append( this.content.$element ); * }; * MyProcessDialog.prototype.getActionProcess = function ( action ) { * var dialog = this; * if ( action ) { * return new OO.ui.Process( function () { * dialog.close( { action: action } ); * } ); * } * return MyProcessDialog.parent.prototype.getActionProcess.call( this, action ); * }; * * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * * var dialog = new MyProcessDialog(); * windowManager.addWindows( [ dialog ] ); * windowManager.openWindow( dialog ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs * * @abstract * @class * @extends OO.ui.Dialog * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ProcessDialog = function OoUiProcessDialog( config ) { // Parent constructor OO.ui.ProcessDialog.parent.call( this, config ); // Properties this.fitOnOpen = false; // Initialization this.$element.addClass( 'oo-ui-processDialog' ); }; /* Setup */ OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog ); /* Methods */ /** * Handle dismiss button click events. * * Hides errors. * * @private */ OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () { this.hideErrors(); }; /** * Handle retry button click events. * * Hides errors and then tries again. * * @private */ OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () { this.hideErrors(); this.executeAction( this.currentAction ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.initialize = function () { // Parent method OO.ui.ProcessDialog.parent.prototype.initialize.call( this ); // Properties this.$navigation = $( '<div>' ); this.$location = $( '<div>' ); this.$safeActions = $( '<div>' ); this.$primaryActions = $( '<div>' ); this.$otherActions = $( '<div>' ); this.dismissButton = new OO.ui.ButtonWidget( { label: OO.ui.msg( 'ooui-dialog-process-dismiss' ) } ); this.retryButton = new OO.ui.ButtonWidget(); this.$errors = $( '<div>' ); this.$errorsTitle = $( '<div>' ); // Events this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } ); this.retryButton.connect( this, { click: 'onRetryButtonClick' } ); // Initialization this.title.$element.addClass( 'oo-ui-processDialog-title' ); this.$location .append( this.title.$element ) .addClass( 'oo-ui-processDialog-location' ); this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' ); this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' ); this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' ); this.$errorsTitle .addClass( 'oo-ui-processDialog-errors-title' ) .text( OO.ui.msg( 'ooui-dialog-process-error' ) ); this.$errors .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' ) .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element ); this.$content .addClass( 'oo-ui-processDialog-content' ) .append( this.$errors ); this.$navigation .addClass( 'oo-ui-processDialog-navigation' ) // Note: Order of appends below is important. These are in the order // we want tab to go through them. Display-order is handled entirely // by CSS absolute-positioning. As such, primary actions like "done" // should go first. .append( this.$primaryActions, this.$location, this.$safeActions ); this.$head.append( this.$navigation ); this.$foot.append( this.$otherActions ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) { var i, len, config, isMobile = OO.ui.isMobile(), widgets = []; for ( i = 0, len = actions.length; i < len; i++ ) { config = $.extend( { framed: !OO.ui.isMobile() }, actions[ i ] ); if ( isMobile && ( config.flags === 'back' || ( Array.isArray( config.flags ) && config.flags.indexOf( 'back' ) !== -1 ) ) ) { $.extend( config, { icon: 'previous', label: '' } ); } widgets.push( new OO.ui.ActionWidget( config ) ); } return widgets; }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.attachActions = function () { var i, len, other, special, others; // Parent method OO.ui.ProcessDialog.parent.prototype.attachActions.call( this ); special = this.actions.getSpecial(); others = this.actions.getOthers(); if ( special.primary ) { this.$primaryActions.append( special.primary.$element ); } for ( i = 0, len = others.length; i < len; i++ ) { other = others[ i ]; this.$otherActions.append( other.$element ); } if ( special.safe ) { this.$safeActions.append( special.safe.$element ); } this.fitLabel(); this.$body.css( 'bottom', this.$foot.outerHeight( true ) ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.executeAction = function ( action ) { var process = this; return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action ) .fail( function ( errors ) { process.showErrors( errors || [] ); } ); }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.setDimensions = function () { // Parent method OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments ); this.fitLabel(); }; /** * Fit label between actions. * * @private * @chainable */ OO.ui.ProcessDialog.prototype.fitLabel = function () { var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth, size = this.getSizeProperties(); if ( typeof size.width !== 'number' ) { if ( this.isOpened() ) { navigationWidth = this.$head.width() - 20; } else if ( this.isOpening() ) { if ( !this.fitOnOpen ) { // Size is relative and the dialog isn't open yet, so wait. this.manager.opening.done( this.fitLabel.bind( this ) ); this.fitOnOpen = true; } return; } else { return; } } else { navigationWidth = size.width - 20; } safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0; primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0; biggerWidth = Math.max( safeWidth, primaryWidth ); labelWidth = this.title.$element.width(); if ( 2 * biggerWidth + labelWidth < navigationWidth ) { // We have enough space to center the label leftWidth = rightWidth = biggerWidth; } else { // Let's hope we at least have enough space not to overlap, because we can't wrap the label… if ( this.getDir() === 'ltr' ) { leftWidth = safeWidth; rightWidth = primaryWidth; } else { leftWidth = primaryWidth; rightWidth = safeWidth; } } this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } ); return this; }; /** * Handle errors that occurred during accept or reject processes. * * @private * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled */ OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) { var i, len, $item, actions, items = [], abilities = {}, recoverable = true, warning = false; if ( errors instanceof OO.ui.Error ) { errors = [ errors ]; } for ( i = 0, len = errors.length; i < len; i++ ) { if ( !errors[ i ].isRecoverable() ) { recoverable = false; } if ( errors[ i ].isWarning() ) { warning = true; } $item = $( '<div>' ) .addClass( 'oo-ui-processDialog-error' ) .append( errors[ i ].getMessage() ); items.push( $item[ 0 ] ); } this.$errorItems = $( items ); if ( recoverable ) { abilities[ this.currentAction ] = true; // Copy the flags from the first matching action actions = this.actions.get( { actions: this.currentAction } ); if ( actions.length ) { this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() ); } } else { abilities[ this.currentAction ] = false; this.actions.setAbilities( abilities ); } if ( warning ) { this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) ); } else { this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) ); } this.retryButton.toggle( recoverable ); this.$errorsTitle.after( this.$errorItems ); this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 ); }; /** * Hide errors. * * @private */ OO.ui.ProcessDialog.prototype.hideErrors = function () { this.$errors.addClass( 'oo-ui-element-hidden' ); if ( this.$errorItems ) { this.$errorItems.remove(); this.$errorItems = null; } }; /** * @inheritdoc */ OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) { // Parent method return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data ) .first( function () { // Make sure to hide errors this.hideErrors(); this.fitOnOpen = false; }, this ); }; /** * @class OO.ui */ /** * Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and * OO.ui.confirm. * * @private * @return {OO.ui.WindowManager} */ OO.ui.getWindowManager = function () { if ( !OO.ui.windowManager ) { OO.ui.windowManager = new OO.ui.WindowManager(); $( 'body' ).append( OO.ui.windowManager.$element ); OO.ui.windowManager.addWindows( [ new OO.ui.MessageDialog() ] ); } return OO.ui.windowManager; }; /** * Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the * rest of the page will be dimmed out and the user won't be able to interact with it. The dialog * has only one action button, labelled "OK", clicking it will simply close the dialog. * * A window manager is created automatically when this function is called for the first time. * * @example * OO.ui.alert( 'Something happened!' ).done( function () { * console.log( 'User closed the dialog.' ); * } ); * * @param {jQuery|string} text Message text to display * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess * @return {jQuery.Promise} Promise resolved when the user closes the dialog */ OO.ui.alert = function ( text, options ) { return OO.ui.getWindowManager().openWindow( 'message', $.extend( { message: text, actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ] }, options ) ).then( function ( opened ) { return opened.then( function ( closing ) { return closing.then( function () { return $.Deferred().resolve(); } ); } ); } ); }; /** * Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open, * the rest of the page will be dimmed out and the user won't be able to interact with it. The * dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it * (labelled "Cancel"). * * A window manager is created automatically when this function is called for the first time. * * @example * OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) { * if ( confirmed ) { * console.log( 'User clicked "OK"!' ); * } else { * console.log( 'User clicked "Cancel" or closed the dialog.' ); * } * } ); * * @param {jQuery|string} text Message text to display * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to * confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean * `false`. */ OO.ui.confirm = function ( text, options ) { return OO.ui.getWindowManager().openWindow( 'message', $.extend( { message: text }, options ) ).then( function ( opened ) { return opened.then( function ( closing ) { return closing.then( function ( data ) { return $.Deferred().resolve( !!( data && data.action === 'accept' ) ); } ); } ); } ); }; /** * Display a quick modal prompt dialog, using a OO.ui.MessageDialog. While the dialog is open, * the rest of the page will be dimmed out and the user won't be able to interact with it. The * dialog has a text input widget and two action buttons, one to confirm an operation (labelled "OK") * and one to cancel it (labelled "Cancel"). * * A window manager is created automatically when this function is called for the first time. * * @example * OO.ui.prompt( 'Choose a line to go to', { textInput: { placeholder: 'Line number' } } ).done( function ( result ) { * if ( result !== null ) { * console.log( 'User typed "' + result + '" then clicked "OK".' ); * } else { * console.log( 'User clicked "Cancel" or closed the dialog.' ); * } * } ); * * @param {jQuery|string} text Message text to display * @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess * @param {Object} [options.textInput] Additional options for text input widget, see OO.ui.TextInputWidget * @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to * confirm, the promise will resolve with the value of the text input widget; otherwise, it will * resolve to `null`. */ OO.ui.prompt = function ( text, options ) { var manager = OO.ui.getWindowManager(), textInput = new OO.ui.TextInputWidget( ( options && options.textInput ) || {} ), textField = new OO.ui.FieldLayout( textInput, { align: 'top', label: text } ); // TODO: This is a little hacky, and could be done by extending MessageDialog instead. return manager.openWindow( 'message', $.extend( { message: textField.$element }, options ) ).then( function ( opened ) { // After ready textInput.on( 'enter', function () { manager.getCurrentWindow().close( { action: 'accept' } ); } ); textInput.focus(); return opened.then( function ( closing ) { return closing.then( function ( data ) { return $.Deferred().resolve( data && data.action === 'accept' ? textInput.getValue() : null ); } ); } ); } ); }; }( OO ) ); //# sourceMappingURL=oojs-ui-windows.js.map
webapp-src/src/MainScreen/BreadCrumbMenuCategory.js
babelouest/taliesin
import React, { Component } from 'react'; import { Breadcrumb } from 'react-bootstrap'; import StateStore from '../lib/StateStore'; class BreadCrumbMenuCategory extends Component { constructor(props) { super(props); this.state = { dataSource: props.dataSource, category: props.category, categoryValue: props.categoryValue, subCategory: props.subCategory, subCategoryValue: props.subCategoryValue, }; this.handleGotoCategory = this.handleGotoCategory.bind(this); this.handleGotoCategoryValue = this.handleGotoCategoryValue.bind(this); this.handleGotoSubcategory = this.handleGotoSubcategory.bind(this); this.handleGotoSubcategoryValue = this.handleGotoSubcategoryValue.bind(this); } componentWillReceiveProps(nextProps) { this.setState({ dataSource: nextProps.dataSource, category: nextProps.category, categoryValue: nextProps.categoryValue, subCategory: nextProps.subCategory, subCategoryValue: nextProps.subCategoryValue }) } handleGotoCategory() { StateStore.dispatch({type: "setCurrentBrowse", browse: "category"}); StateStore.dispatch({type: "setCurrentCategory", category: this.state.category}); } handleGotoCategoryValue() { StateStore.dispatch({type: "setCurrentBrowse", browse: "category"}); StateStore.dispatch({type: "setCurrentCategory", category: this.state.category, categoryValue: this.state.categoryValue}); } handleGotoSubcategory() { StateStore.dispatch({type: "setCurrentBrowse", browse: "category"}); StateStore.dispatch({type: "setCurrentCategory", category: this.state.category, categoryValue: this.state.categoryValue, subCategory: this.state.subCategory}); } handleGotoSubcategoryValue() { StateStore.dispatch({type: "setCurrentBrowse", browse: "category"}); StateStore.dispatch({type: "setCurrentCategory", category: this.state.category, categoryValue: this.state.categoryValue, subCategory: this.state.subCategory, subCategoryValue: this.state.subCategoryValue}); } render() { var breadcrumbList = [ <Breadcrumb.Item key={0} onClick={this.handleGotoCategory}> {this.state.category} </Breadcrumb.Item> ]; if (this.state.categoryValue) { breadcrumbList.push( <Breadcrumb.Item key={1} onClick={this.handleGotoCategoryValue}> {this.state.categoryValue} </Breadcrumb.Item> ) if (this.state.subCategory) { breadcrumbList.push( <Breadcrumb.Item key={2} onClick={this.handleGotoSubcategory}> {this.state.subCategory} </Breadcrumb.Item> ) if (this.state.subCategoryValue) { breadcrumbList.push( <Breadcrumb.Item key={3} onClick={this.handleGotoSubcategoryValue}> {this.state.subCategoryValue} </Breadcrumb.Item> ) } } } return ( <Breadcrumb> <Breadcrumb.Item> {this.state.dataSource} </Breadcrumb.Item> {breadcrumbList} </Breadcrumb> ); } } export default BreadCrumbMenuCategory;
ajax/libs/antd/1.11.2/antd.min.js
dlueth/cdnjs
/*! * antd v1.11.2 * * Copyright 2015-present, Alipay, Inc. * All rights reserved. */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.antd=t(require("react"),require("react-dom")):e.antd=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var n=t.slice(1),r=e[t[0]];return function(e,t,o){r.apply(this,[e,t,o].concat(n))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,n){e.exports=n(306)},function(t,n){t.exports=e},function(e,t,n){var r,o;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var a in r)i.call(r,a)&&r[a]&&e.push(a)}}return e.join(" ")}var i={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(r=[],o=function(){return n}.apply(t,r),!(void 0!==o&&(e.exports=o)))}()},function(e,t){},function(e,n){e.exports=t},function(e,t,n){"use strict";function r(e,t){t.every(function(e){return"string"==typeof e})&&m(e,t)}function o(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=1,o=t[0],i=t.length;if("function"==typeof o)return o.apply(null,t.slice(1));if("string"==typeof o){for(var a=String(o).replace(v,function(e){if("%%"===e)return"%";if(r>=i)return e;switch(e){case"%s":return String(t[r++]);case"%d":return Number(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch(n){return"[Circular]"}break;default:return e}}),s=t[r];r<i;s=t[++r])a+=" "+s;return a}return o}function i(e){return"string"===e||"url"===e||"hex"===e||"email"===e}function a(e,t){return void 0===e||null===e||(!("array"!==t||!Array.isArray(e)||e.length)||!(!i(t)||"string"!=typeof e||e))}function s(e){return 0===Object.keys(e).length}function l(e,t,n){function r(e){o.push.apply(o,e),i++,i===a&&n(o)}var o=[],i=0,a=e.length;e.forEach(function(e){t(e,r)})}function u(e,t,n){function r(a){if(a&&a.length)return void n(a);var s=o;o+=1,s<i?t(e[s],r):n([])}var o=0,i=e.length;r([])}function c(e){var t=[];return Object.keys(e).forEach(function(n){t.push.apply(t,e[n])}),t}function p(e,t,n,r){if(t.first){var o=c(e);return u(o,n,r)}var i=t.firstFields||[];i===!0&&(i=Object.keys(e));var a=Object.keys(e),s=a.length,p=0,f=[],d=function(e){f.push.apply(f,e),p++,p===s&&r(f)};a.forEach(function(t){var r=e[t];i.indexOf(t)!==-1?u(r,n,d):l(r,n,d)})}function f(e){return function(t){return t&&t.message?(t.field=t.field||e.fullField,t):{message:t,field:t.field||e.fullField}}}function d(e,t){if(t)for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];"object"===("undefined"==typeof r?"undefined":y(r))&&"object"===y(e[n])?e[n]=h({},e[n],r):e[n]=r}return e}Object.defineProperty(t,"__esModule",{value:!0});var h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},y="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.warning=r,t.format=o,t.isEmptyValue=a,t.isEmptyObject=s,t.asyncMap=p,t.complementError=f,t.deepMerge=d;var v=/%[sdj%]/g,m=function(){}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),s=r(a);t["default"]=function(e){var t=e.type,n=e.className,r=void 0===n?"":n,a=o(e,["type","className"]);return r+=" anticon anticon-"+t,s["default"].createElement("i",i({className:r.trim()},a))},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(308),i=r(o);t["default"]=i["default"]||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={required:n(87),whitespace:n(185),type:n(184),range:n(183),"enum":n(181),pattern:n(182)},e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(387)},function(e,t){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(i){return!1}}var o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,a,s=n(e),l=1;l<arguments.length;l++){r=Object(arguments[l]);for(var u in r)o.call(r,u)&&(s[u]=r[u]);if(Object.getOwnPropertySymbols){a=Object.getOwnPropertySymbols(r);for(var c=0;c<a.length;c++)i.call(r,a[c])&&(s[a[c]]=r[a[c]])}}return s}},function(e,t){var n=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(310),i=r(o);t["default"]=function(e,t,n){return t in e?(0,i["default"])(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){var r=n(72)("wks"),o=n(52),i=n(17).Symbol,a="function"==typeof i,s=e.exports=function(e){return r[e]||(r[e]=a&&i[e]||(a?i:o)("Symbol."+e))};s.store=r},function(e,t,n){"use strict";function r(e){var t=e||p;this.locale=t,this.fields=[],this.time=void 0,this.timezoneOffset=t.timezoneOffset,this.firstDayOfWeek=t.firstDayOfWeek,this.minimalDaysInFirstWeek=t.minimalDaysInFirstWeek,this.fieldsComputed=!1}function o(e,t){return L(e)?S[t]:E[t]}function i(e){return L(e)?366:365}function a(e){var t=e.fields,n=t[h],r=t[y],i=o(n,r),a=t[v];a>i&&e.set(v,i)}function s(e,t){return e-A(e-t,7)}function l(e,t,n){var r=s(t+6,e.firstDayOfWeek),o=r-t;o>=e.minimalDaysInFirstWeek&&(r-=7);var i=n-r;return V(i/7)+1}var u=parseInt,c=n(375),p=n(133),f=n(132);c.mix(r,f),c.mix(r,{Utils:c,defaultLocale:p,isLeapYear:c.isLeapYear,YEAR:1,MONTH:2,DAY_OF_MONTH:3,HOUR_OF_DAY:4,MINUTES:5,SECONDS:6,MILLISECONDS:7,WEEK_OF_YEAR:8,WEEK_OF_MONTH:9,DAY_OF_YEAR:10,DAY_OF_WEEK:11,DAY_OF_WEEK_IN_MONTH:12,AM:0,PM:1});var d=["","Year","Month","DayOfMonth","HourOfDay","Minutes","Seconds","Milliseconds","WeekOfYear","WeekOfMonth","DayOfYear","DayOfWeek","DayOfWeekInMonth"],h=r.YEAR,y=r.MONTH,v=r.DAY_OF_MONTH,m=r.HOUR_OF_DAY,g=r.MINUTES,b=r.SECONDS,P=r.MILLISECONDS,C=r.DAY_OF_WEEK_IN_MONTH,T=r.DAY_OF_YEAR,O=r.DAY_OF_WEEK,w=r.WEEK_OF_MONTH,x=r.WEEK_OF_YEAR,E=[31,28,31,30,31,30,31,31,30,31,30,31],S=[31,29,31,30,31,30,31,31,30,31,30,31],k=1e3,N=60*k,j=60*N,_=24*j,M=7*_,D=719163,A=c.mod,L=c.isLeapYear,V=Math.floor,I=[void 0,1,r.JANUARY,1,0,0,0,0,1,void 0,1,r.SUNDAY,1],F=[void 0,292278994,r.DECEMBER,void 0,23,59,59,999,void 0,void 0,void 0,r.SATURDAY,void 0];r.prototype={constructor:r,isGregorianCalendar:1,isLeapYear:function(){return L(this.getYear())},getLocale:function(){return this.locale},getActualMinimum:function(e){if(void 0!==I[e])return I[e];if(e===w){var t=this.clone();return t.clear(),t.set(this.fields[h],this.fields[y],1),t.get(w)}throw new Error("minimum value not defined!")},getActualMaximum:function(e){if(void 0!==F[e])return F[e];var t=void 0,n=this.fields;switch(e){case v:t=o(n[h],n[y]);break;case x:var a=this.clone();a.clear(),a.set(n[h],r.DECEMBER,31),t=a.get(x),1===t&&(t=52);break;case w:var s=this.clone();s.clear(),s.set(n[h],n[y],o(n[h],n[y])),t=s.get(w);break;case T:t=i(n[h]);break;case C:t=u((o(n[h],n[y])-1)/7)+1}if(void 0===t)throw new Error("maximum value not defined!");return t},isSet:function(e){return void 0!==this.fields[e]},computeFields:function(){var e=this.time,t=this.timezoneOffset*N,n=u(t/_),o=t%_;if(n+=u(e/_),o+=e%_,o>=_)o-=_,n++;else for(;o<0;)o+=_,n--;n+=D;var a=c.getGregorianDateFromFixedDate(n),p=a.year,f=this.fields;if(f[h]=p,f[y]=a.month,f[v]=a.dayOfMonth,f[O]=a.dayOfWeek,0!==o){f[m]=u(o/j);var d=o%j;f[g]=u(d/N),d%=N,f[b]=u(d/k),f[P]=d%k}else f[m]=f[g]=f[b]=f[P]=0;var E=c.getFixedDate(p,r.JANUARY,1),S=n-E+1,M=n-a.dayOfMonth+1;f[T]=S,f[C]=u((a.dayOfMonth-1)/7)+1;var A=l(this,E,n);if(0===A){var L=E-1,V=E-i(p-1);A=l(this,V,L)}else if(A>=52){var I=E+i(p),F=s(I+6,this.firstDayOfWeek),R=F-I;R>=this.minimalDaysInFirstWeek&&n>=F-7&&(A=1)}f[x]=A,f[w]=l(this,M,n),this.fieldsComputed=!0},computeTime:function(){var e=void 0,t=this.fields;e=this.isSet(h)?t[h]:(new Date).getFullYear();var n=0;this.isSet(m)&&(n+=t[m]),n*=60,n+=t[g]||0,n*=60,n+=t[b]||0,n*=1e3,n+=t[P]||0;var r=0;t[h]=e,r+=this.getFixedDate();var o=(r-D)*_+n;o-=this.timezoneOffset*N,this.time=o,this.computeFields()},complete:function(){void 0===this.time&&this.computeTime(),this.fieldsComputed||this.computeFields()},getFixedDate:function(){var e=this,t=e.fields,n=e.firstDayOfWeek,i=t[h],a=r.JANUARY;e.isSet(y)&&(a=t[y],a>r.DECEMBER?(i+=u(a/12),a%=12):a<r.JANUARY&&(i+=V(a/12),a=A(a,12)));var l=c.getFixedDate(i,a,1),p=void 0,f=e.firstDayOfWeek;if(e.isSet(O)&&(f=t[O]),e.isSet(y))if(e.isSet(v))l+=t[v]-1;else if(e.isSet(w))p=s(l+6,n),p-l>=e.minimalDaysInFirstWeek&&(p-=7),f!==n&&(p=s(p+6,f)),l=p+7*(t[w]-1);else{var d=void 0;d=e.isSet(C)?t[C]:1;var m=7*d;d<0&&(m=o(i,a)+7*(d+1)),l=s(l+m-1,f)}else e.isSet(T)?l+=t[T]-1:e.isSet(x)&&(p=s(l+6,n),p-l>=e.minimalDaysInFirstWeek&&(p-=7),f!==n&&(p=s(p+6,f)),l=p+7*(t[x]-1));return l},getTime:function(){return void 0===this.time&&this.computeTime(),this.time},setTime:function(e){this.time=e,this.fieldsComputed=!1,this.complete()},get:function(e){return this.complete(),this.fields[e]},set:function(e,t){var n=arguments.length;if(2===n)this.fields[e]=t;else{if(!(n<P+1))throw new Error("illegal arguments for GregorianCalendar set");for(var r=0;r<n;r++)this.fields[h+r]=arguments[r]}this.time=void 0},add:function(e,t){if(t){var n=t,r=this,o=r.fields,i=r.get(e);if(e===h)i+=n,r.set(h,i),a(r);else if(e===y){i+=n;var s=V(i/12);i=A(i,12),s&&r.set(h,o[h]+s),r.set(y,i),a(r)}else{switch(e){case m:n*=j;break;case g:n*=N;break;case b:n*=k;break;case P:break;case w:case x:case C:n*=M;break;case O:case T:case v:n*=_;break;default:throw new Error("illegal field for add")}r.setTime(r.time+n)}}},getRolledValue:function(e,t,n,r){var o=t,i=e-n,a=r-n+1;return o%=a,n+(i+o+a)%a},roll:function(e,t){if(t){var n=this,r=n.get(e),o=n.getActualMinimum(e),i=n.getActualMaximum(e);switch(r=n.getRolledValue(r,t,o,i),n.set(e,r),e){case y:a(n);break;default:n.updateFieldsBySet(e)}}},rollSet:function(e,t){switch(this.set(e,t),e){case y:a(this);break;default:this.updateFieldsBySet(e)}},updateFieldsBySet:function(e){var t=this.fields;switch(e){case w:t[v]=void 0;break;case T:t[y]=void 0;break;case O:t[v]=void 0;break;case x:t[T]=void 0,t[y]=void 0}},getTimezoneOffset:function(){return this.timezoneOffset},setTimezoneOffset:function(e){this.timezoneOffset!==e&&(this.fieldsComputed=void 0,this.timezoneOffset=e)},setFirstDayOfWeek:function(e){this.firstDayOfWeek!==e&&(this.firstDayOfWeek=e,this.fieldsComputed=!1)},getFirstDayOfWeek:function(){return this.firstDayOfWeek},setMinimalDaysInFirstWeek:function(e){this.minimalDaysInFirstWeek!==e&&(this.minimalDaysInFirstWeek=e,this.fieldsComputed=!1)},getMinimalDaysInFirstWeek:function(){return this.minimalDaysInFirstWeek},getWeeksInWeekYear:function(){var e=this.getWeekYear();if(e===this.get(h))return this.getActualMaximum(x);var t=this.clone();return t.clear(),t.setWeekDate(e,2,this.get(O)),t.getActualMaximum(x)},getWeekYear:function(){var e=this.get(h),t=this.get(x),n=this.get(y);return n===r.JANUARY?t>=52&&--e:n===r.DECEMBER&&1===t&&++e,e},setWeekDate:function(e,t,n){if(n<r.SUNDAY||n>r.SATURDAY)throw new Error("invalid dayOfWeek: "+n);var o=this.fields,i=this.clone();i.clear(),i.setTimezoneOffset(0),i.set(h,e),i.set(x,1),i.set(O,this.getFirstDayOfWeek());var a=n-this.getFirstDayOfWeek();a<0&&(a+=7),a+=7*(t-1),0!==a?i.add(T,a):i.complete(),o[h]=i.get(h),o[y]=i.get(y),o[v]=i.get(v),this.complete()},clone:function(){void 0===this.time&&this.computeTime();var e=new r(this.locale);return e.setTimezoneOffset(e.getTimezoneOffset()),e.setFirstDayOfWeek(e.getFirstDayOfWeek()),e.setMinimalDaysInFirstWeek(e.getMinimalDaysInFirstWeek()),e.setTime(this.time),e},equals:function(e){return this.getTime()===e.getTime()&&this.firstDayOfWeek===e.firstDayOfWeek&&this.timezoneOffset===e.timezoneOffset&&this.minimalDaysInFirstWeek===e.minimalDaysInFirstWeek},compareToDay:function(e){var t=this.getYear(),n=e.getYear(),r=this.getMonth(),o=e.getMonth(),i=this.getDayOfMonth(),a=e.getDayOfMonth();return t!==n?t-n:r!==o?r-o:i-a},clear:function(e){void 0===e?this.field=[]:this.fields[e]=void 0,this.time=void 0,this.fieldsComputed=!1},toString:function(){var e=this;return"[GregorianCalendar]: "+e.getYear()+"/"+e.getMonth()+"/"+e.getDayOfMonth()+" "+e.getHourOfDay()+":"+e.getMinutes()+":"+e.getSeconds()}};var R=r.prototype;c.each(d,function(e,t){e&&(R["get"+e]=function(){return this.get(t)},R["isSet"+e]=function(){return this.isSet(t)},R["set"+e]=function(e){return this.set(t,e)},R["add"+e]=function(e){return this.add(t,e)},R["roll"+e]=function(e){return this.roll(t,e)},R["rollSet"+e]=function(e){return this.rollSet(t,e)})}),e.exports=r},function(e,t){"use strict";var n={MAC_ENTER:3,BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,QUESTION_MARK:63,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,META:91,WIN_KEY_RIGHT:92,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUMLOCK:144,SEMICOLON:186,DASH:189,EQUALS:187,COMMA:188,PERIOD:190,SLASH:191,APOSTROPHE:192,SINGLE_QUOTE:222,OPEN_SQUARE_BRACKET:219,BACKSLASH:220,CLOSE_SQUARE_BRACKET:221,WIN_KEY:224,MAC_FF_META:224,WIN_IME:229};n.isTextModifyingKeyEvent=function(e){var t=e.keyCode;if(e.altKey&&!e.ctrlKey||e.metaKey||t>=n.F1&&t<=n.F12)return!1;switch(t){case n.ALT:case n.CAPS_LOCK:case n.CONTEXT_MENU:case n.CTRL:case n.DOWN:case n.END:case n.ESC:case n.HOME:case n.INSERT:case n.LEFT:case n.MAC_FF_META:case n.META:case n.NUMLOCK:case n.NUM_CENTER:case n.PAGE_DOWN:case n.PAGE_UP:case n.PAUSE:case n.PRINT_SCREEN:case n.RIGHT:case n.SHIFT:case n.UP:case n.WIN_KEY:case n.WIN_KEY_RIGHT:return!1;default:return!0}},n.isCharacterKey=function(e){if(e>=n.ZERO&&e<=n.NINE)return!0;if(e>=n.NUM_ZERO&&e<=n.NUM_MULTIPLY)return!0;if(e>=n.A&&e<=n.Z)return!0;if(window.navigation.userAgent.indexOf("WebKit")!==-1&&0===e)return!0;switch(e){case n.SPACE:case n.QUESTION_MARK:case n.NUM_PLUS:case n.NUM_MINUS:case n.NUM_PERIOD:case n.NUM_DIVISION:case n.SEMICOLON:case n.DASH:case n.EQUALS:case n.COMMA:case n.PERIOD:case n.SLASH:case n.APOSTROPHE:case n.SINGLE_QUOTE:case n.OPEN_SQUARE_BRACKET:case n.BACKSLASH:case n.CLOSE_SQUARE_BRACKET:return!0;default:return!1}},e.exports=n},function(e,t,n){var r=n(17),o=n(11),i=n(64),a=n(32),s="prototype",l=function(e,t,n){var u,c,p,f=e&l.F,d=e&l.G,h=e&l.S,y=e&l.P,v=e&l.B,m=e&l.W,g=d?o:o[t]||(o[t]={}),b=g[s],P=d?r:h?r[t]:(r[t]||{})[s];d&&(n=t);for(u in n)c=!f&&P&&void 0!==P[u],c&&u in g||(p=c?P[u]:n[u],g[u]=d&&"function"!=typeof P[u]?n[u]:v&&c?i(p,r):m&&P[u]==p?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t[s]=e[s],t}(p):y&&"function"==typeof p?i(Function.call,p):p,y&&((g.virtual||(g.virtual={}))[u]=p,e&l.R&&b&&!b[u]&&a(b,u,p)))};l.F=1,l.G=2,l.S=4,l.P=8,l.B=16,l.W=32,l.U=64,l.R=128,e.exports=l},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var r=n(30),o=n(121),i=n(74),a=Object.defineProperty;t.f=n(24)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return a(e,t,n)}catch(s){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.clone();return t.setTime(Date.now()),t}function i(e){return e.getYear()+"-"+(e.getMonth()+1)+"-"+e.getDayOfMonth()}function a(e){var t=o(e);return i(t)}function s(e,t){return"string"==typeof e?new y["default"](e,t.format):e}function l(e,t){t.setHourOfDay(e.getHourOfDay()),t.setMinutes(e.getMinutes()),t.setSeconds(e.getSeconds())}function u(e,t){var n=t?t(e):{};return n=d({},v,n)}function c(e,t){var n=!1;if(e){var r=e.getHourOfDay(),o=e.getMinutes(),i=e.getSeconds(),a=t.disabledHours();if(a.indexOf(r)===-1){var s=t.disabledMinutes(r);if(s.indexOf(o)===-1){var l=t.disabledSeconds(r,o);n=l.indexOf(i)!==-1}else n=!0}else n=!0}return!n}function p(e,t){var n=u(e,t);return c(e,n)}function f(e,t,n){return(!t||!t(e))&&!(n&&!p(e,n))}Object.defineProperty(t,"__esModule",{value:!0});var d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.getTodayTime=o,t.getTitleString=i,t.getTodayTimeStr=a,t.getFormatter=s,t.syncTime=l,t.getTimeConfig=u,t.isTimeValidByConfig=c,t.isTimeValid=p,t.isAllowedDate=f;var h=n(53),y=r(h),v={disabledHours:function(){return[]},disabledMinutes:function(){return[]},disabledSeconds:function(){return[]}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){var r=l["default"].unstable_batchedUpdates?function(e){l["default"].unstable_batchedUpdates(n,e)}:n;return(0,a["default"])(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var i=n(178),a=r(i),s=n(4),l=r(s);e.exports=t["default"]},function(e,t,n){e.exports=n(512)},function(e,t,n){"use strict";var r=function(){};e.exports=r},[557,532],function(e,t,n){e.exports=!n(31)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(122),o=n(65);e.exports=function(e){return r(o(e))}},function(e,t,n){/*! * object.omit <https://github.com/jonschlinkert/object.omit> * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ "use strict";var r=n(377),o=n(373);e.exports=function(e,t){if(!r(e))return{};var n,t=[].concat.apply([],[].slice.call(arguments,1)),i=t[t.length-1],a={};"function"==typeof i&&(n=t.pop());var s="function"==typeof n;return t.length||s?(o(e,function(r,o){t.indexOf(o)===-1&&(s?n(r,o,e)&&(a[o]=r):a[o]=r)}),a):e}},function(e,t,n){"use strict";e.exports=n(492)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(213),i=r(o),a=n(212),s=r(a);i["default"].Group=s["default"],t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){var r=n(36);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t){e.exports=function(e){try{return!!e()}catch(t){return!0}}},function(e,t,n){var r=n(18),o=n(38);e.exports=n(24)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(126),o=n(66);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(149),h=r(d),y=n(1),v=r(y),m=n(224),g=r(m),b=n(2),P=r(b),C=n(21),T=r(C),O=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return T["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.style,o=t.children,s=t.className,l=a(t,["prefixCls","style","children","className"]),u=(0,P["default"])((e={},i(e,s,!!s),i(e,n+"-wrapper",!0),e));return v["default"].createElement("label",{className:u,style:r},v["default"].createElement(h["default"],f({},l,{prefixCls:n,children:null})),void 0!==o?v["default"].createElement("span",null,o):null)},t}(v["default"].Component),c.Group=g["default"],c.defaultProps={prefixCls:"ant-checkbox"},p);t["default"]=O,e.exports=t["default"]},[557,526],function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports={}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){"use strict";function r(e,t){return e+t}function o(e,t,n){var r=n;{if("object"!==("undefined"==typeof t?"undefined":x(t)))return"undefined"!=typeof r?("number"==typeof r&&(r+="px"),void(e.style[t]=r)):k(e,t);for(var i in t)t.hasOwnProperty(i)&&o(e,i,t[i])}}function i(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,i=o.body,a=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=a.clientLeft||i.clientLeft||0,r-=a.clientTop||i.clientTop||0,{left:n,top:r}}function a(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function s(e){return a(e)}function l(e){return a(e,!0)}function u(e){var t=i(e),n=e.ownerDocument,r=n.defaultView||n.parentWindow;return t.left+=s(r),t.top+=l(r),t}function c(e,t,n){var r=n,o="",i=e.ownerDocument;return r=r||i.defaultView.getComputedStyle(e,null),r&&(o=r.getPropertyValue(t)||r[t]),o}function p(e,t){var n=e[_]&&e[_][t];if(N.test(n)&&!j.test(t)){var r=e.style,o=r[D],i=e[M][D];e[M][D]=e[_][D],r[D]="fontSize"===t?"1em":n||0,n=r.pixelLeft+A,r[D]=o,e[M][D]=i}return""===n?"auto":n}function f(e,t){return"left"===e?t.useCssRight?"right":e:t.useCssBottom?"bottom":e}function d(e){return"left"===e?"right":"right"===e?"left":"top"===e?"bottom":"bottom"===e?"top":void 0}function h(e,t,n){"static"===o(e,"position")&&(e.style.position="relative");var i=-999,a=-999,s=f("left",n),l=f("top",n),c=d(s),p=d(l);"left"!==s&&(i=999),"top"!==l&&(a=999);var h="",y=u(e);("left"in t||"top"in t)&&(h=(0,E.getTransitionProperty)(e)||"",(0,E.setTransitionProperty)(e,"none")),"left"in t&&(e.style[c]="",e.style[s]=i+"px"),"top"in t&&(e.style[p]="",e.style[l]=a+"px");var v=u(e),m={};for(var g in t)if(t.hasOwnProperty(g)){var b=f(g,n),P="left"===g?i:a,C=y[g]-v[g];b===g?m[b]=P+C:m[b]=P-C}o(e,m),r(e.offsetTop,e.offsetLeft),("left"in t||"top"in t)&&(0,E.setTransitionProperty)(e,h);var T={};for(var O in t)if(t.hasOwnProperty(O)){var w=f(O,n),x=t[O]-y[O];O===w?T[w]=m[w]+x:T[w]=m[w]-x}o(e,T)}function y(e,t){var n=u(e),r=(0,E.getTransformXY)(e),o={x:r.x,y:r.y};"left"in t&&(o.x=r.x+t.left-n.left),"top"in t&&(o.y=r.y+t.top-n.top),(0,E.setTransformXY)(e,o)}function v(e,t,n){n.useCssRight||n.useCssBottom?h(e,t,n):n.useCssTransform&&(0,E.getTransformName)()in document.body.style?y(e,t,n):h(e,t,n)}function m(e,t){for(var n=0;n<e.length;n++)t(e[n])}function g(e){return"border-box"===k(e,"boxSizing")}function b(e,t,n){var r={},o=e.style,i=void 0;for(i in t)t.hasOwnProperty(i)&&(r[i]=o[i],o[i]=t[i]);n.call(e);for(i in t)t.hasOwnProperty(i)&&(o[i]=r[i])}function P(e,t,n){var r=0,o=void 0,i=void 0,a=void 0;for(i=0;i<t.length;i++)if(o=t[i])for(a=0;a<n.length;a++){var s=void 0;s="border"===o?""+o+n[a]+"Width":o+n[a],r+=parseFloat(k(e,s))||0}return r}function C(e){return null!==e&&void 0!==e&&e==e.window}function T(e,t,n){var r=n;if(C(e))return"width"===t?K.viewportWidth(e):K.viewportHeight(e);if(9===e.nodeType)return"width"===t?K.docWidth(e):K.docHeight(e);var o="width"===t?["Left","Right"]:["Top","Bottom"],i="width"===t?e.offsetWidth:e.offsetHeight,a=k(e),s=g(e,a),l=0;(null===i||void 0===i||i<=0)&&(i=void 0,l=k(e,t),(null===l||void 0===l||Number(l)<0)&&(l=e.style[t]||0),l=parseFloat(l)||0),void 0===r&&(r=s?F:V);var u=void 0!==i||s,c=i||l;return r===V?u?c-P(e,["border","padding"],o,a):l:u?r===F?c:c+(r===I?-P(e,["border"],o,a):P(e,["margin"],o,a)):l+P(e,L.slice(r),o,a)}function O(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=void 0,o=t[0];return 0!==o.offsetWidth?r=T.apply(void 0,t):b(o,W,function(){r=T.apply(void 0,t)}),r}function w(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}Object.defineProperty(t,"__esModule",{value:!0});var x="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},E=n(367),S=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,k=void 0,N=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),j=/^(top|right|bottom|left)$/,_="currentStyle",M="runtimeStyle",D="left",A="px";"undefined"!=typeof window&&(k=window.getComputedStyle?c:p);var L=["margin","border","padding"],V=-1,I=2,F=1,R=0,K={};m(["Width","Height"],function(e){K["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],K["viewport"+e](n))},K["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,i=r.documentElement,a=i[n];return"CSS1Compat"===r.compatMode&&a||o&&o[n]||a}});var W={position:"absolute",visibility:"hidden",display:"block"};m(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);K["outer"+t]=function(t,n){return t&&O(t,e,n?R:F)};var n="width"===e?["Left","Right"]:["Top","Bottom"];K[e]=function(t,r){var i=r;{if(void 0===i)return t&&O(t,e,V);if(t){var a=k(t),s=g(t);return s&&(i+=P(t,["padding","border"],n,a)),o(t,e,i)}}}});var H={getWindow:function(e){if(e&&e.document&&e.setTimeout)return e;var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},offset:function(e,t,n){return"undefined"==typeof t?u(e):void v(e,t,n||{})},isWindow:C,each:m,css:o,clone:function(e){var t=void 0,n={};for(t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);var r=e.overflow;if(r)for(t in e)e.hasOwnProperty(t)&&(n.overflow[t]=e.overflow[t]);return n},mix:w,getWindowScrollLeft:function(e){return s(e)},getWindowScrollTop:function(e){return l(e)},merge:function(){for(var e={},t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var o=0;o<n.length;o++)H.mix(e,n[o]);return e},viewportWidth:0,viewportHeight:0};w(H,K),t["default"]=H,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Divider=t.ItemGroup=t.MenuItemGroup=t.MenuItem=t.Item=t.SubMenu=void 0;var o=n(423),i=r(o),a=n(426),s=r(a),l=n(424),u=r(l),c=n(425),p=r(c),f=n(422),d=r(f);t.SubMenu=s["default"],t.Item=u["default"],t.MenuItem=u["default"],t.MenuItemGroup=p["default"],t.ItemGroup=p["default"],t.Divider=d["default"],t["default"]=i["default"]},function(e,t,n){"use strict";var r=n(381);e.exports=function(e,t,n,o){var i=n?n.call(o,e,t):void 0;if(void 0!==i)return!!i;if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var a=r(e),s=r(t),l=a.length;if(l!==s.length)return!1;o=o||null;for(var u=Object.prototype.hasOwnProperty.bind(t),c=0;c<l;c++){var p=a[c];if(!u(p))return!1;var f=e[p],d=t[p],h=n?n.call(o,f,d,p):void 0;if(h===!1||void 0===h&&f!==d)return!1}return!0}},[557,521],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(60),i=r(o),a=n(268),s=r(a),l=n(107),u=r(l);i["default"].Button=u["default"],i["default"].Group=s["default"],t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(451),y=r(h),v=n(2),m=r(v),g=(c=u=function(e){function t(){return a(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.size,r=t.className,o=t.combobox,a=t.notFoundContent,s=t.prefixCls,l=t.showSearch,u=t.optionLabelProp,c=(0,m["default"])((e={},i(e,s+"-lg","large"===n),i(e,s+"-sm","small"===n),i(e,r,!!r),i(e,s+"-show-search",l),e)),f=this.context.antLocale;return f&&f.Select&&(a=a||f.Select.notFoundContent),o&&(a=null,u=u||"value"),d["default"].createElement(y["default"],p({},this.props,{className:c,optionLabelProp:u||"children",notFoundContent:a}))},t}(d["default"].Component),u.Option=h.Option,u.OptGroup=h.OptGroup,u.defaultProps={prefixCls:"ant-select",transitionName:"slide-up",choiceTransitionName:"zoom",showSearch:!1},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=g,e.exports=t["default"]},[558,542],function(e,t){"use strict";t.__esModule=!0,t["default"]=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(311),i=r(o),a=n(309),s=r(a),l=n(49),u=r(l);t["default"]=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+("undefined"==typeof t?"undefined":(0,u["default"])(t)));e.prototype=(0,s["default"])(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(i["default"]?(0,i["default"])(e,t):e.__proto__=t)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(49),i=r(o);t["default"]=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==("undefined"==typeof t?"undefined":(0,i["default"])(t))&&"function"!=typeof t?e:t}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(313),i=r(o),a=n(312),s=r(a),l="function"==typeof s["default"]&&"symbol"==typeof i["default"]?function(e){return typeof e}:function(e){return e&&"function"==typeof s["default"]&&e.constructor===s["default"]?"symbol":typeof e};t["default"]="function"==typeof s["default"]&&"symbol"===l(i["default"])?function(e){return"undefined"==typeof e?"undefined":l(e)}:function(e){return e&&"function"==typeof s["default"]&&e.constructor===s["default"]?"symbol":"undefined"==typeof e?"undefined":l(e)}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(65);e.exports=function(e){return Object(r(e))}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t,n){"use strict";function r(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}function o(e,t,n){return"string"==typeof e&&t?e.replace(n||O,function(e,n){return"\\"===e.charAt(0)?e.slice(1):void 0===t[n]?w:t[n]}):e}function i(e,t,n){n.push({field:e,count:t})}function a(e){for(var t=e.length,n=!1,r=[],o=null,a=0,s=-1,l=0;l<t;l++){var u=e.charAt(l);if("'"!==u)if(n)o+=u;else if(u>="a"&&u<="z"||u>="A"&&u<="Z"){if(P.indexOf(u)===-1)throw new Error('Illegal pattern character "'+u+'"');s!==-1&&s!==u?(i(s,a,r),s=u,a=1):(s=u,a++)}else 0!==a&&(i(s,a,r),s=-1,a=0),r.push({text:u});else{if(l+1<t&&(u=e.charAt(l+1),"'"===u)){l++,0!==a&&(i(s,a,r),s=-1,a=0),n&&(o+=u);continue}n?(r.push({text:o}),n=!1):(0!==a&&(i(s,a,r),s=-1,a=0),o="",n=!0)}}if(n)throw new Error("Unterminated quote");return 0!==a&&i(s,a,r),r}function s(e,t,n,r){var o=!0;e:for(;o;){var i=e,a=t,s=n,l=r;o=!1;var u=l||[],c=s||m;if(i>=0){if(i<100&&a>=1&&a<=2)return i<10&&2===a&&u.push(x),u.push(i),u.join("");if(i>=1e3&&i<1e4){if(4===a)return u.push(i),u.join("");if(2===a&&2===c){e=i%100,t=2,n=2,r=u,o=!0,u=c=void 0;continue e}}}return u.push(i+""),u.join("")}}function l(e,t){this.locale=t||v,this.originalPattern=e,this.pattern=a(e)}function u(e,t,n,r){var o=void 0,i=void 0;switch(e){case"G":i=r.getYear()>0?1:0,o=n.eras[i];break;case"Y":i=r.getWeekYear(),i<=0&&(i=1-i),o=s(i,2,2!==t?m:2);break;case"y":i=r.getYear(),i<=0&&(i=1-i),o=s(i,2,2!==t?m:2);break;case"M":i=r.getMonth(),o=t>=4?n.months[i]:3===t?n.shortMonths[i]:s(i+1,t);break;case"k":o=s(r.getHourOfDay()||24,t);break;case"E":i=r.getDayOfWeek(),o=t>=4?n.weekdays[i]:n.shortWeekdays[i];break;case"a":o=n.ampms[r.getHourOfDay()>=12?1:0];break;case"h":o=s(r.getHourOfDay()%12||12,t);break;case"K":o=s(r.getHourOfDay()%12,t);break;case"Z":var a=r.getTimezoneOffset(),l=[a<0?"-":"+"];a=Math.abs(a),l.push(s(Math.floor(a/60)%100,2),s(a%60,2)),o=l.join("");break;default:var u=T[e];i=r.get(u),o=s(i,t)}return o}function c(e,t,n,r){for(var o=0;o<r;o++)if(e.charAt(t+o)!==n.charAt(o))return!1;return!0}function p(e,t,n){var r=-1,o=-1,i=void 0,a=n.length;for(i=0;i<a;i++){var s=n[i],l=s.length;l>r&&c(e,t,s,l)&&(r=l,o=i)}return o>=0?{value:o,startIndex:t+r}:null}function f(e){var t=void 0,n=void 0,r=e.length;for(t=0;t<r&&(n=e.charAt(t),!(n<"0"||n>"9"));t++);return t}function d(e,t,n,r){var o=e,i=void 0;if(r){if(e.length<t+n)return null;if(o=e.slice(t,t+n),!o.match(/^\d+$/))throw new Error("GregorianCalendarFormat parse error, dateStr: "+e+", patter: "+this.originalPattern)}else o=o.slice(t);if(i=parseInt(o,10),isNaN(i))throw new Error("GregorianCalendarFormat parse error, dateStr: "+e+", patter: "+this.originalPattern);return{value:i,startIndex:t+f(o)}}function h(e,t,n,r,o,i,a){var s=void 0,l=void 0,u=void 0,c=n;if(t.length<=c)return c;var f=this.locale;switch(r){case"G":s=p(t,c,f.eras),s&&(e.isSetYear()?0===s.value&&(l=e.getYear(),e.setYear(1-l)):a.era=s.value);break;case"y":s=d.call(this,t,c,o,i),s&&(l=s.value,"era"in a&&0===a.era&&(l=1-l),e.setYear(l));break;case"M":var h=void 0;o>=3?(s=p(t,c,f[3===o?"shortMonths":"months"]),s&&(h=s.value)):(s=d.call(this,t,c,o,i),s&&(h=s.value-1)),s&&e.setMonth(h);break;case"k":s=d.call(this,t,c,o,i),s&&e.setHourOfDay(s.value%24);break;case"E":s=p(t,c,f[o>3?"weekdays":"shortWeekdays"]),s&&e.setDayOfWeek(s.value);break;case"a":s=p(t,c,f.ampms),s&&(e.isSetHourOfDay()?s.value&&(u=e.getHourOfDay(),u<12&&e.setHourOfDay((u+12)%24)):a.ampm=s.value);break;case"h":s=d.call(this,t,c,o,i),s&&(u=s.value%=12,a.ampm&&(u+=12),e.setHourOfDay(u));break;case"K":s=d.call(this,t,c,o,i),s&&(u=s.value,a.ampm&&(u+=12),e.setHourOfDay(u));break;case"Z":var y=t.charAt(c);if("-"===y)c++;else{if("+"!==y)break;c++}if(s=d.call(this,t,c,2,!0)){var v=60*s.value;c=s.startIndex,s=d.call(this,t,c,2,!0),s&&(v+=s.value),e.setTimezoneOffset(v)}break;default:if(s=d.call(this,t,c,o,i)){var m=T[r];e.set(m,s.value)}}return s&&(c=s.startIndex),c}var y=n(14),v=n(79),m=Number.MAX_VALUE,g=n(374),b={FULL:0,LONG:1,MEDIUM:2,SHORT:3},P=new Array(y.DAY_OF_WEEK_IN_MONTH+2).join("1"),C=0,T={};P=P.split(""),P[C]="G",P[y.YEAR]="y",P[y.MONTH]="M",P[y.DAY_OF_MONTH]="d",P[y.HOUR_OF_DAY]="H",P[y.MINUTES]="m",P[y.SECONDS]="s",P[y.MILLISECONDS]="S",P[y.WEEK_OF_YEAR]="w",P[y.WEEK_OF_MONTH]="W",P[y.DAY_OF_YEAR]="D",P[y.DAY_OF_WEEK_IN_MONTH]="F",P.push("Y"),P.forEach(function(e,t){var n=t;"Y"===e&&(n=y.YEAR),e&&(T[e]=n)});var O=/\\?\{([^{}]+)\}/g,w="";P=P.join("")+"ahkKZE";var x="0";r(l.prototype,{format:function(e){if(!e.isGregorianCalendar)throw new Error("calendar must be type of GregorianCalendar");var t=void 0,n=[],r=this.pattern,o=r.length;for(t=0;t<o;t++){var i=r[t];i.text?n.push(i.text):"field"in i&&n.push(u(i.field,i.count,this.locale,e))}return n.join("")},parse:function(e,t){var n=t||{},r=n.locale,o=new y(r),i=void 0,a=void 0,s={},l=n.obeyCount||!1,u=e.length,c=-1,p=0,f=0,d=this.pattern,v=d.length;e:for(i=0;c<0&&i<v;i++){var m=d[i],b=void 0,P=void 0;if(f=p,b=m.text)if(P=b.length,P+p>u)c=p;else{for(a=0;a<P;a++)if(b.charAt(a)!==e.charAt(a+p)){c=p;break e}p+=P}else if("field"in m){if(!n.obeyCount){var C=d[i+1];if(l=!1,C)if("field"in C)l=!0;else{var T=C.text.charAt(0);T>="0"&&T<="9"&&(l=!0)}}p=h.call(this,o,e,p,m.field,m.count,l,s),p===f&&(c=p)}}return c>=0?void g(!1,"error when parsing date: "+e+", position: "+e.slice(0,c)+"^"):o}}),r(l,{Style:b,getInstance:function(e){return this.getDateTimeInstance(b.SHORT,b.SHORT,e)},getDateInstance:function(e,t){return this.getDateTimeInstance(e,void 0,t)},getDateTimeInstance:function(e,t,n){var r=n||v,i="";void 0!==e&&(i=r.datePatterns[e]);var a="";void 0!==t&&(a=r.timePatterns[t]);var s=i;return a&&(s=i?o(r.dateTimePattern,{date:i,time:a}):a),new l(s,r)},getTimeInstance:function(e,t){return this.getDateTimeInstance(void 0,e,t)}}),e.exports=l,l.version="@VERSION@"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=n(398),s=r(a),l=n(19);t["default"]={propTypes:{className:i.PropTypes.string,locale:i.PropTypes.object,style:i.PropTypes.object,visible:i.PropTypes.bool,onSelect:i.PropTypes.func,prefixCls:i.PropTypes.string,onChange:i.PropTypes.func,onOk:i.PropTypes.func},getDefaultProps:function(){return{locale:s["default"],style:{},visible:!0,prefixCls:"rc-calendar",formatter:"yyyy-MM-dd",className:"",onSelect:o,onChange:o,onClear:o}},shouldComponentUpdate:function(e){return this.props.visible||e.visible},getFormatter:function(){var e=this.props.formatter,t=this.props.locale;return this.normalFormatter&&e===this.lastFormatter?this.normalFormatter:(this.normalFormatter=(0,l.getFormatter)(e,t),this.lastFormatter=e,this.normalFormatter)},focus:function(){this.refs.root&&this.refs.root.focus()}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e,t,n){var r=t||"";return e.key||r+"item_"+c+"_"+n}function a(e,t){var n=-1;u["default"].Children.forEach(e,function(e){n++,e&&e.type.isMenuItemGroup?u["default"].Children.forEach(e.props.children,function(e){n++,t(e,n)}):t(e,n)})}function s(e,t,n){e&&!n.find&&u["default"].Children.forEach(e,function(e){if(!n.find&&e){var r=e.type;if(!r||!(r.isSubMenu||r.isMenuItem||r.isMenuItemGroup))return;t.indexOf(e.key)!==-1?n.find=!0:e.props.children&&s(e.props.children,t,n)}})}Object.defineProperty(t,"__esModule",{value:!0}),t.noop=o,t.getKeyFromChildrenIndex=i,t.loopMenuItem=a,t.loopMenuItemRecusively=s;var l=n(1),u=r(l),c=Date.now()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.props;if("value"in t)return t.value;if(e.key)return e.key;throw new Error("no key or value for "+e)}function i(e,t){return"value"===t?o(e):e.props[t]}function a(e){return e.combobox}function s(e){return e.multiple||e.tags}function l(e){return s(e)||a(e)}function u(e){return!l(e)}function c(e){var t=e;return void 0===e?t=[]:Array.isArray(e)||(t=[e]),t}function p(e){e.preventDefault()}function f(e,t){for(var n=-1,r=0;r<e.length;r++)if(e[r].key===t){n=r;break}return n}function d(e,t){if(null===t||void 0===t)return[];var n=[];return m["default"].Children.forEach(e,function(e){if(e.type===y.ItemGroup)n=n.concat(d(e.props.children,t));else{var r=o(e),i=e.key;f(t,r)!==-1&&i&&n.push(i)}}),n}function h(e){for(var t=0;t<e.length;t++){var n=e[t];if(n.type===y.ItemGroup){var r=h(n.props.children);if(r)return r}else if(!n.props.disabled)return n}return null}Object.defineProperty(t,"__esModule",{value:!0}),t.UNSELECTABLE_ATTRIBUTE=t.UNSELECTABLE_STYLE=void 0,t.getValuePropValue=o,t.getPropValue=i,t.isCombobox=a,t.isMultipleOrTags=s,t.isMultipleOrTagsOrCombobox=l,t.isSingleMode=u,t.toArray=c,t.preventDefaultEvent=p,t.findIndexInValueByKey=f,t.getSelectKeys=d,t.findFirstMenuItem=h;var y=n(40),v=n(1),m=r(v);t.UNSELECTABLE_STYLE={userSelect:"none",WebkitUserSelect:"none"},t.UNSELECTABLE_ATTRIBUTE={unselectable:"unselectable"}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=e.type,l=[],u=e.required||!e.required&&r.hasOwnProperty(e.field);if(u){if((0,s.isEmptyValue)(t,i)&&!e.required)return n();a["default"].required(e,t,r,l,o,i),(0,s.isEmptyValue)(t,i)||a["default"].type(e,t,r,l,o)}n(l)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Col=t.Row=void 0;var o=n(247),i=r(o),a=n(246),s=r(a);t.Row=i["default"],t.Col=s["default"]},function(e,t,n){"use strict";function r(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];if(!e.arrowPointAtCenter)return o.placements;var t=e.arrowWidth,n=void 0===t?5:t,r=e.horizontalArrowShift,s=void 0===r?16:r,l=e.verticalArrowShift,u=void 0===l?12:l;return{left:{points:["cr","cl"],overflow:i,offset:[-4,0],targetOffset:a},right:{points:["cl","cr"],overflow:i,offset:[4,0],targetOffset:a},top:{points:["bc","tc"],overflow:i,offset:[0,-4],targetOffset:a},bottom:{points:["tc","bc"],overflow:i,offset:[0,4],targetOffset:a},topLeft:{points:["bl","tc"],overflow:i,offset:[-(s+n),-4],targetOffset:a},leftTop:{points:["tr","cl"],overflow:i,offset:[-4,-(u+n)],targetOffset:a},topRight:{points:["br","tc"],overflow:i,offset:[s+n,-4],targetOffset:a},rightTop:{points:["tl","cr"],overflow:i,offset:[4,-(u+n)],targetOffset:a},bottomRight:{points:["tr","bc"],overflow:i,offset:[s+n,4],targetOffset:a},rightBottom:{points:["bl","cr"],overflow:i,offset:[4,u+n],targetOffset:a},bottomLeft:{points:["tl","bc"],overflow:i,offset:[-(s+n),4],targetOffset:a},leftBottom:{points:["br","cl"],overflow:i,offset:[-4,u+n],targetOffset:a}}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var o=n(163),i={adjustX:1,adjustY:1},a=[0,0];e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(442),d=r(f),h=n(1),y=r(h),v=n(2),m=r(v),g=n(21),b=r(g),P=(c=u=function(e){function t(){return a(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return b["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.children,a=n.checked,s=n.disabled,l=n.className,u=n.style,c=(0,m["default"])((e={},i(e,r+"-wrapper",!0),i(e,r+"-wrapper-checked",a),i(e,r+"-wrapper-disabled",s),i(e,l,!!l),e)),f=(0,m["default"])((t={},i(t,""+r,!0),i(t,r+"-checked",a),i(t,r+"-disabled",s),t));return y["default"].createElement("label",{className:c,style:u},y["default"].createElement(d["default"],p({},this.props,{className:f,style:null,children:null})),o?y["default"].createElement("span",null,o):null)},t}(y["default"].Component),u.defaultProps={prefixCls:"ant-radio"},c);t["default"]=P,e.exports=t["default"]},[557,540],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(162),h=r(d),y=n(59),v=r(y),m=(u=l=function(e){function t(n){i(this,t);var r=a(this,e.call(this,n));return r.onVisibleChange=function(e){r.setState({visible:e}),r.props.onVisibleChange(e)},r.onPopupAlign=function(e,t){var n=r.getPlacements(),o=Object.keys(n).filter(function(e){return n[e].points[0]===t.points[0]&&n[e].points[1]===t.points[1]})[0];if(o){var i=e.getBoundingClientRect(),a={top:"50%",left:"50%"};o.indexOf("top")>=0||o.indexOf("Bottom")>=0?a.top=i.height-t.offset[1]+"px":(o.indexOf("Top")>=0||o.indexOf("bottom")>=0)&&(a.top=-t.offset[1]+"px"),o.indexOf("left")>=0||o.indexOf("Right")>=0?a.left=i.width-t.offset[0]+"px":(o.indexOf("right")>=0||o.indexOf("Left")>=0)&&(a.left=-t.offset[0]+"px"),e.style.transformOrigin=a.left+" "+a.top}},r.state={visible:!1},r}return s(t,e),t.prototype.getPopupDomNode=function(){return this.refs.tooltip.getPopupDomNode()},t.prototype.getPlacements=function(){var e=this.props,t=e.builtinPlacements,n=e.arrowPointAtCenter;return t||(0,v["default"])({arrowPointAtCenter:n,verticalArrowShift:8})},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.title,r=e.overlay,o=e.children,i=this.state.visible;n||r||(i=!1),"visible"in this.props&&(i=this.props.visible);var a=this.props.openClassName||t+"-open",s=o&&o.props&&o.props.className?o.props.className+" "+a:a;return f["default"].createElement(h["default"],c({overlay:n,visible:i,onPopupAlign:this.onPopupAlign,ref:"tooltip"},this.props,{builtinPlacements:this.getPlacements(),onVisibleChange:this.onVisibleChange}),i?(0,p.cloneElement)(o,{className:s}):o)},t}(f["default"].Component),l.defaultProps={prefixCls:"ant-tooltip",placement:"top",transitionName:"zoom-big",mouseEnterDelay:.1,mouseLeaveDelay:.1,onVisibleChange:function(){},arrowPointAtCenter:!1},u);t["default"]=m,e.exports=t["default"]},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(324);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){e.exports=!0},function(e,t,n){var r=n(30),o=n(340),i=n(66),a=n(71)("IE_PROTO"),s=function(){},l="prototype",u=function(){var e,t=n(120)("iframe"),r=i.length,o="<",a=">";for(t.style.display="none",n(330).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(o+"script"+a+"document.F=Object"+o+"/script"+a),e.close(),u=e.F;r--;)delete u[l][i[r]];return u()};e.exports=Object.create||function(e,t){var n;return null!==e?(s[l]=r(e),n=new s,s[l]=null,n[a]=e):n=u(),void 0===t?n:o(n,t)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(18).f,o=n(25),i=n(13)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){var r=n(72)("keys"),o=n(52);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){var r=n(17),o="__core-js_shared__",i=r[o]||(r[o]={});e.exports=function(e){return i[e]||(i[e]={})}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(36);e.exports=function(e,t){if(!r(e))return e; var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){var r=n(17),o=n(11),i=n(67),a=n(76),s=n(18).f;e.exports=function(e){var t=o.Symbol||(o.Symbol=i?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||s(t,e,{value:a.f(e)})}},function(e,t,n){t.f=n(13)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=window.getComputedStyle(e),r="",o=0;o<h.length&&!(r=n.getPropertyValue(h[o]+t));o++);return r}function i(e){if(f){var t=parseFloat(o(e,"transition-delay"))||0,n=parseFloat(o(e,"transition-duration"))||0,r=parseFloat(o(e,"animation-delay"))||0,i=parseFloat(o(e,"animation-duration"))||0,a=Math.max(n+t,i+r);e.rcEndAnimTimeout=setTimeout(function(){e.rcEndAnimTimeout=null,e.rcEndListener&&e.rcEndListener()},1e3*a+200)}}function a(e){e.rcEndAnimTimeout&&(clearTimeout(e.rcEndAnimTimeout),e.rcEndAnimTimeout=null)}Object.defineProperty(t,"__esModule",{value:!0});var s="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},l=n(360),u=r(l),c=n(118),p=r(c),f=0!==u["default"].endEvents.length,d=["Webkit","Moz","O","ms"],h=["-webkit-","-moz-","-o-","ms-",""],y=function(e,t,n){var r="object"===("undefined"==typeof t?"undefined":s(t)),o=r?t.name:t,l=r?t.active:t+"-active",c=n,f=void 0,d=void 0,h=(0,p["default"])(e);return n&&"[object Object]"===Object.prototype.toString.call(n)&&(c=n.end,f=n.start,d=n.active),e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),a(e),h.remove(o),h.remove(l),u["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,c&&c())},u["default"].addEndEventListener(e,e.rcEndListener),f&&f(),h.add(o),e.rcAnimTimeout=setTimeout(function(){e.rcAnimTimeout=null,h.add(l),d&&setTimeout(d,0),i(e)},30),{stop:function(){e.rcEndListener&&e.rcEndListener()}}};y.style=function(e,t,n){e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),a(e),u["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,n&&n())},u["default"].addEndEventListener(e,e.rcEndListener),e.rcAnimTimeout=setTimeout(function(){for(var n in t)t.hasOwnProperty(n)&&(e.style[n]=t[n]);e.rcAnimTimeout=null,i(e)},0)},y.setTransition=function(e,t,n){var r=t,o=n;void 0===n&&(o=r,r=""),r=r||"",d.forEach(function(t){e.style[t+"Transition"+r]=o})},y.isCssAnimationSupported=f,t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(368)},function(e,t){"use strict";e.exports={eras:["BC","AD"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],weekdays:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortWeekdays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],veryShortWeekdays:["Su","Mo","Tu","We","Th","Fr","Sa"],ampms:["AM","PM"],datePatterns:["EEEE, MMMM d, yyyy","MMMM d, yyyy","MMM d, yyyy","M/d/yy"],timePatterns:["h:mm:ss a 'GMT'Z","h:mm:ss a","h:mm:ss a","h:mm a"],dateTimePattern:"{date} {time}"}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=n(395),p=r(c),f=n(394),d=r(f),h=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.prefixCls;return u["default"].createElement("table",{className:t+"-table",cellSpacing:"0",role:"grid"},u["default"].createElement(p["default"],e),u["default"].createElement(d["default"],e))},t}(u["default"].Component);t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(){}function a(){var e=new d["default"];return e.setTime(Date.now()),e}function s(e){var t=void 0;return e?(t=e.clone(),t.setTime(Date.now())):t=a(),t}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=n(2),p=r(c),f=n(14),d=r(f),h=n(19),y={propTypes:{value:l.PropTypes.object,defaultValue:l.PropTypes.object,onKeyDown:l.PropTypes.func},getDefaultProps:function(){return{onKeyDown:i}},getInitialState:function(){var e=this.props,t=e.value||e.defaultValue||a();return{value:t,selectedValue:e.selectedValue||e.defaultSelectedValue}},componentWillReceiveProps:function(e){var t=e.value,n=e.selectedValue;"value"in e&&(t=t||e.defaultValue||s(this.state.value),this.setState({value:t})),"selectedValue"in e&&this.setState({selectedValue:n})},onSelect:function(e,t){e&&this.setValue(e),this.setSelectedValue(e,t)},renderRoot:function(e){var t,n=this.props,r=n.prefixCls,i=(t={},o(t,r,1),o(t,r+"-hidden",!n.visible),o(t,n.className,!!n.className),o(t,e.className,!!e.className),t);return u["default"].createElement("div",{ref:"root",className:""+(0,p["default"])(i),style:this.props.style,tabIndex:"0",onKeyDown:this.onKeyDown},e.children)},setSelectedValue:function(e,t){this.isAllowedDate(e)&&("selectedValue"in this.props||this.setState({selectedValue:e}),this.props.onSelect(e,t))},setValue:function(e){var t=this.state.value;"value"in this.props||this.setState({value:e}),(t&&e&&t.getTime()!==e.getTime()||!t&&e||t&&!e)&&this.props.onChange(e)},isAllowedDate:function(e){var t=this.props.disabledDate,n=this.props.disabledTime;return(0,h.isAllowedDate)(e,t,n)}};t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(46),i=r(o),a=n(48),s=r(a),l=n(47),u=r(l),c=n(1),p=r(c),f=function(e){function t(){return(0,i["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t}(p["default"].Component);t["default"]=f,e.exports=t["default"]},function(e,t){"use strict";function n(){var e=arguments;return function(){for(var t=0;t<e.length;t++)e[t]&&e[t].apply&&e[t].apply(this,arguments)}}e.exports=n},function(e,t,n){(function(e,r){function o(e,t){this._id=e,this._clearFn=t}var i=n(383).nextTick,a=Function.prototype.apply,s=Array.prototype.slice,l={},u=0;t.setTimeout=function(){return new o(a.call(setTimeout,window,arguments),clearTimeout)},t.setInterval=function(){return new o(a.call(setInterval,window,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(window,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},t.setImmediate="function"==typeof e?e:function(e){var n=u++,r=!(arguments.length<2)&&s.call(arguments,1);return l[n]=!0,i(function(){l[n]&&(r?e.apply(null,r):e.call(null),t.clearImmediate(n))}),n},t.clearImmediate="function"==typeof r?r:function(e){delete l[e]}}).call(t,n(84).setImmediate,n(84).clearImmediate)},3,function(e,t){function n(e,t,n){n=n||{},n.childrenKeyName=n.childrenKeyName||"children";var r,o=e||[],i=[],a=0;do{var r=o.filter(function(e){return t(e,a)})[0];if(!r)break;i.push(r),o=r[n.childrenKeyName]||[],a+=1}while(o.length>0);return i}e.exports=n},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o,i){!e.required||n.hasOwnProperty(e.field)&&!a.isEmptyValue(t,i)||r.push(a.format(o.messages.required,e.fullField))}Object.defineProperty(t,"__esModule",{value:!0});var i=n(5),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(){if(void 0!==r)return r;var e="Webkit Moz O ms Khtml".split(" "),t=document.createElement("div");if(void 0!==t.style.animationName&&(r=!0),void 0!==r)for(var n=0;n<e.length;n++)if(void 0!==t.style[e[n]+"AnimationName"]){r=!0;break}return r=r||!1}Object.defineProperty(t,"__esModule",{value:!0});var r=void 0;t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){var r=void 0;return(0,a["default"])(e,"ant-motion-collapse",{start:function(){t?(r=e.offsetHeight,e.style.height=0):e.style.height=e.offsetHeight+"px"},active:function(){e.style.height=(t?r:0)+"px"},end:function(){e.style.height="",n()}})}Object.defineProperty(t,"__esModule",{value:!0});var i=n(77),a=r(i),s={enter:function(e,t){return o(e,!0,t)},leave:function(e,t){return o(e,!1,t)},appear:function(e,t){return o(e,!0,t)}};t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=(c=u=function(e){function t(){return a(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.separator,r=e.children,o=i(e,["prefixCls","separator","children"]),a=void 0;return a="href"in this.props?d["default"].createElement("a",p({className:t+"-link"},o),r):d["default"].createElement("span",p({className:t+"-link"},o),r),d["default"].createElement("span",null,a,d["default"].createElement("span",{className:t+"-separator"},n))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-breadcrumb",separator:"/"},u.propTypes={prefixCls:d["default"].PropTypes.string,separator:d["default"].PropTypes.oneOfType([d["default"].PropTypes.string,d["default"].PropTypes.element]),href:d["default"].PropTypes.string},c);t["default"]=h,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.PREFIX_CLS="ant-fullcalendar"},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(58);t["default"]=r.Col,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(134),a=r(i),s=n(145),l=r(s),u=n(111),c=r(u),p=o({},a["default"]);p.lang=o({placeholder:"\u8bf7\u9009\u62e9\u65e5\u671f",rangePlaceholder:["\u5f00\u59cb\u65e5\u671f","\u7ed3\u675f\u65e5\u671f"]},l["default"]),p.timePickerLocale=o({},c["default"]),p.lang.ok="\u786e \u5b9a",t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(415),d=r(f),h=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(d["default"],this.props)},t}(p["default"].Component),l.defaultProps={transitionName:"slide-up",prefixCls:"ant-dropdown",mouseEnterDelay:.15,mouseLeaveDelay:.1},u);t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(94),i=r(o),a=n(234),s=r(a);i["default"].Button=s["default"],t["default"]=i["default"],e.exports=t["default"]},[559,529],function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.FIELD_META_PROP="data-__meta"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(244),i=r(o),a=n(243),s=r(a);i["default"].Group=s["default"],t["default"]=i["default"],e.exports=t["default"]},[557,85],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(413),y=r(h),v=n(20),m=r(v),g=n(29),b=r(g),P=void 0,C=void 0,T=(c=u=function(e){function t(){var n,r,o;i(this,t);for(var s=arguments.length,l=Array(s),u=0;u<s;u++)l[u]=arguments[u];return n=r=a(this,e.call.apply(e,[this].concat(l))),r.handleCancel=function(e){r.props.onCancel(e)},r.handleOk=function(){r.props.onOk()},o=n,a(r,o)}return s(t,e),t.prototype.componentDidMount=function(){C||((0,m["default"])(document.documentElement,"click",function(e){P={x:e.pageX,y:e.pageY},setTimeout(function(){return P=null},20)}),C=!0)},t.prototype.render=function(){var e=this.props,t=e.okText,n=e.cancelText,r=e.confirmLoading,o=e.footer,i=e.visible;this.context.antLocale&&this.context.antLocale.Modal&&(t=t||this.context.antLocale.Modal.okText,n=n||this.context.antLocale.Modal.cancelText);var a=[d["default"].createElement(b["default"],{key:"cancel",type:"ghost",size:"large",onClick:this.handleCancel},n||"\u53d6\u6d88"),d["default"].createElement(b["default"],{key:"confirm",type:"primary",size:"large",loading:r,onClick:this.handleOk},t||"\u786e\u5b9a")];return d["default"].createElement(y["default"],p({onClose:this.handleCancel,footer:o||a},this.props,{visible:i,mousePosition:P}))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-modal",onOk:l,onCancel:l,width:520,transitionName:"zoom",maskTransitionName:"fade",confirmLoading:!1,visible:!1},u.propTypes={prefixCls:f.PropTypes.string,onOk:f.PropTypes.func,onCancel:f.PropTypes.func,okText:f.PropTypes.node,cancelText:f.PropTypes.node,width:f.PropTypes.oneOfType([f.PropTypes.number,f.PropTypes.string]),confirmLoading:f.PropTypes.bool,visible:f.PropTypes.bool,align:f.PropTypes.object,footer:f.PropTypes.node,title:f.PropTypes.node,closable:f.PropTypes.bool},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=T,e.exports=t["default"]},function(e,t){"use strict";function n(e){a=e?o({},a,e):o({},i)}function r(){return a}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.changeConfirmLocale=n,t.getConfirmLocale=r;var i={okText:"\u786e\u5b9a",cancelText:"\u53d6\u6d88",justOkText:"\u77e5\u9053\u4e86"},a=o({},i)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(260),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(537),n(45),n(23)},[557,538],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(265),l=r(s),u=n(22),c=r(u),p=l["default"];p.Line=function(e){return(0,c["default"])(!1,'<Progress.Line /> is deprecated, use <Progress type="line" /> instead.'),a["default"].createElement(l["default"],o({},e,{type:"line"}))},p.Circle=function(e){return(0,c["default"])(!1,'<Progress.Circle /> is deprecated, use <Progress type="circle" /> instead.'),a["default"].createElement(l["default"],o({},e,{type:"circle"}))},t["default"]=p,e.exports=t["default"]},[557,539],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(60),d=r(f),h=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(d["default"],this.props)},t}(p["default"].Component),l.defaultProps={prefixCls:"ant-radio-button"},u);t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(58);t["default"]=r.Row,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(4),v=n(2),m=r(v),g=n(88),b=r(g),P=n(22),C=r(P),T=n(27),O=r(T),w=(p=c=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n)),o=r.getSpinning(n);return r.state={spinning:o},r}return u(t,e),t.prototype.isNestedPattern=function(){return!(!this.props||!this.props.children)},t.prototype.componentDidMount=function(){(0,C["default"])(!("spining"in this.props),"`spining` property of Popover is a spell mistake, use `spinning` instead."),(0,b["default"])()||((0,y.findDOMNode)(this).className+=" "+this.props.prefixCls+"-show-text")},t.prototype.componentWillUnmount=function(){this.debounceTimeout&&clearTimeout(this.debounceTimeout)},t.prototype.getSpinning=function(e){return"spining"in e?((0,C["default"])(!1,"`spining` property of Spin is a spell mistake, use `spinning` instead."),e.spining):e.spinning},t.prototype.componentWillReceiveProps=function(e){var t=this,n=this.getSpinning(this.props),r=this.getSpinning(e);this.debounceTimeout&&clearTimeout(this.debounceTimeout),n&&!r?this.debounceTimeout=setTimeout(function(){return t.setState({spinning:r})},500):this.setState({spinning:r})},t.prototype.render=function(){var e,t=this.props,n=t.className,r=t.size,o=t.prefixCls,s=t.tip,l=a(t,["className","size","prefixCls","tip"]),u=this.state.spinning,c=(0,m["default"])((e={},i(e,o,!0),i(e,o+"-sm","small"===r),i(e,o+"-lg","large"===r),i(e,o+"-spinning",u),i(e,o+"-show-text",!!this.props.tip),i(e,n,!!n),e)),p=(0,O["default"])(l,["spinning"]),d=h["default"].createElement("div",f({},p,{className:c}),h["default"].createElement("span",{className:o+"-dot"}),h["default"].createElement("div",{className:o+"-text"},s||"\u52a0\u8f7d\u4e2d..."));return this.isNestedPattern()?h["default"].createElement("div",f({},p,{className:u?o+"-nested-loading":""}),d,h["default"].createElement("div",{className:o+"-container"},this.props.children)):d},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-spin",spinning:!0},c.propTypes={className:h["default"].PropTypes.string,size:h["default"].PropTypes.oneOf(["small","default","large"])},p);t["default"]=w,e.exports=t["default"]},[557,544],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(476),a=r(i),s=o({placeholder:"\u8bf7\u9009\u62e9\u65f6\u95f4"},a["default"]);t["default"]=s,e.exports=t["default"]},[558,550],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.color,s=n.last,l=n.children,u=n.pending,c=n.className,p=n.dot,d=a(n,["prefixCls","color","last","children","pending","className","dot"]),y=(0,v["default"])((e={},i(e,r+"-item",!0),i(e,r+"-item-last",s),i(e,r+"-item-pending",u),i(e,c,c),e)),m=(0,v["default"])((t={},i(t,r+"-item-head",!0),i(t,r+"-item-head-custom",p),i(t,r+"-item-head-"+o,!0),t));return h["default"].createElement("li",f({},d,{className:y}),h["default"].createElement("div",{className:r+"-item-tail"}),h["default"].createElement("div",{className:m,style:{borderColor:/blue|red|green/.test(o)?null:o}},p),h["default"].createElement("div",{className:r+"-item-content"},l))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-timeline",color:"blue",last:!1,pending:!1},p);t["default"]=m,e.exports=t["default"]},[557,552],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(6),h=r(d),y=(c=u=function(e){function t(){var n,r,o;i(this,t);for(var s=arguments.length,l=Array(s),u=0;u<s;u++)l[u]=arguments[u];return n=r=a(this,e.call.apply(e,[this].concat(l))),r.handleChange=function(e){r.props.onChange(e)},r.handleClear=function(e){e.preventDefault(),r.props.handleClear(e)},o=n,a(r,o)}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.placeholder,n=e.value,r=e.prefixCls;return f["default"].createElement("div",null,f["default"].createElement("input",{placeholder:t,className:r+" ant-input",value:n,ref:"input",onChange:this.handleChange}),n&&n.length>0?f["default"].createElement("a",{href:"#",className:r+"-action",onClick:this.handleClear},f["default"].createElement(h["default"],{type:"cross-circle"})):f["default"].createElement("span",{className:r+"-action"},f["default"].createElement(h["default"],{type:"search"})))},t}(f["default"].Component),u.defaultProps={placeholder:"",onChange:l,handleClear:l},u.propTypes={prefixCls:p.PropTypes.string,placeholder:p.PropTypes.string,onChange:p.PropTypes.func,handleClear:p.PropTypes.func},c);t["default"]=y,e.exports=t["default"]},function(e,t,n){e.exports={"default":n(320),__esModule:!0}},function(e,t){"use strict";t.__esModule=!0,t["default"]=function(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}},function(e,t,n){function r(e){if(!e||!e.nodeType)throw new Error("A DOM element reference is required");this.el=e,this.list=e.classList}try{var o=n(119)}catch(i){var o=n(119)}var a=/\s+/,s=Object.prototype.toString;e.exports=function(e){return new r(e)},r.prototype.add=function(e){if(this.list)return this.list.add(e),this;var t=this.array(),n=o(t,e);return~n||t.push(e),this.el.className=t.join(" "),this},r.prototype.remove=function(e){if("[object RegExp]"==s.call(e))return this.removeMatching(e);if(this.list)return this.list.remove(e),this;var t=this.array(),n=o(t,e);return~n&&t.splice(n,1),this.el.className=t.join(" "),this},r.prototype.removeMatching=function(e){for(var t=this.array(),n=0;n<t.length;n++)e.test(t[n])&&this.remove(t[n]);return this},r.prototype.toggle=function(e,t){return this.list?("undefined"!=typeof t?t!==this.list.toggle(e,t)&&this.list.toggle(e):this.list.toggle(e),this):("undefined"!=typeof t?t?this.add(e):this.remove(e):this.has(e)?this.remove(e):this.add(e),this)},r.prototype.array=function(){var e=this.el.getAttribute("class")||"",t=e.replace(/^\s+|\s+$/g,""),n=t.split(a);return""===n[0]&&n.shift(),n},r.prototype.has=r.prototype.contains=function(e){return this.list?this.list.contains(e):!!~o(this.array(),e)}},function(e,t){e.exports=function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;n<e.length;++n)if(e[n]===t)return n;return-1}},function(e,t,n){var r=n(36),o=n(17).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){e.exports=!n(24)&&!n(31)(function(){return 7!=Object.defineProperty(n(120)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(63);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t,n){"use strict";var r=n(67),o=n(16),i=n(127),a=n(32),s=n(25),l=n(37),u=n(334),c=n(70),p=n(342),f=n(13)("iterator"),d=!([].keys&&"next"in[].keys()),h="@@iterator",y="keys",v="values",m=function(){return this};e.exports=function(e,t,n,g,b,P,C){u(n,t,g);var T,O,w,x=function(e){if(!d&&e in N)return N[e];switch(e){case y:return function(){return new n(this,e)};case v:return function(){return new n(this,e)}}return function(){return new n(this,e)}},E=t+" Iterator",S=b==v,k=!1,N=e.prototype,j=N[f]||N[h]||b&&N[b],_=j||x(b),M=b?S?x("entries"):_:void 0,D="Array"==t?N.entries||j:j;if(D&&(w=p(D.call(new e)),w!==Object.prototype&&(c(w,E,!0),r||s(w,f)||a(w,f,m))),S&&j&&j.name!==v&&(k=!0,_=function(){return j.call(this)}),r&&!C||!d&&!k&&N[f]||a(N,f,_),l[t]=_,l[E]=m,b)if(T={values:S?_:x(v),keys:P?_:x(y),entries:M},C)for(O in T)O in N||i(N,O,T[O]);else o(o.P+o.F*(d||k),t,T);return T}},function(e,t,n){var r=n(50),o=n(38),i=n(26),a=n(74),s=n(25),l=n(121),u=Object.getOwnPropertyDescriptor;t.f=n(24)?u:function(e,t){if(e=i(e),t=a(t,!0),l)try{return u(e,t)}catch(n){} if(s(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(126),o=n(66).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,o)}},function(e,t,n){var r=n(25),o=n(26),i=n(326)(!1),a=n(71)("IE_PROTO");e.exports=function(e,t){var n,s=o(e),l=0,u=[];for(n in s)n!=a&&r(s,n)&&u.push(n);for(;t.length>l;)r(s,n=t[l++])&&(~i(u,n)||u.push(n));return u}},function(e,t,n){e.exports=n(32)},function(e,t,n){var r=n(73),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){"use strict";var r=n(345)(!0);n(123)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.ownerDocument,n=t.body,r=void 0,o=a["default"].css(e,"position"),i="fixed"===o||"absolute"===o;if(!i)return"html"===e.nodeName.toLowerCase()?null:e.parentNode;for(r=e.parentNode;r&&r!==n;r=r.parentNode)if(o=a["default"].css(r,"position"),"static"!==o)return r;return null}Object.defineProperty(t,"__esModule",{value:!0});var i=n(39),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";e.exports={eras:["\u516c\u5143\u524d","\u516c\u5143"],months:["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"],shortMonths:["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"],weekdays:["\u661f\u671f\u5929","\u661f\u671f\u4e00","\u661f\u671f\u4e8c","\u661f\u671f\u4e09","\u661f\u671f\u56db","\u661f\u671f\u4e94","\u661f\u671f\u516d"],shortWeekdays:["\u5468\u65e5","\u5468\u4e00","\u5468\u4e8c","\u5468\u4e09","\u5468\u56db","\u5468\u4e94","\u5468\u516d"],veryShortWeekdays:["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"],ampms:["\u4e0a\u5348","\u4e0b\u5348"],datePatterns:["yyyy'\u5e74'M'\u6708'd'\u65e5' EEEE","yyyy'\u5e74'M'\u6708'd'\u65e5'","yyyy-M-d","yy-M-d"],timePatterns:["ahh'\u65f6'mm'\u5206'ss'\u79d2' 'GMT'Z","ahh'\u65f6'mm'\u5206'ss'\u79d2'","H:mm:ss","ah:mm"],dateTimePattern:"{date} {time}"}},function(e,t){"use strict";e.exports={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6,JANUARY:0,FEBRUARY:1,MARCH:2,APRIL:3,MAY:4,JUNE:5,JULY:6,AUGUST:7,SEPTEMBER:8,OCTOBER:9,NOVEMBER:10,DECEMBER:11}},function(e,t){"use strict";e.exports={timezoneOffset:-480,firstDayOfWeek:0,minimalDaysInFirstWeek:1}},function(e,t){"use strict";e.exports={timezoneOffset:480,firstDayOfWeek:1,minimalDaysInFirstWeek:1}},function(e,t,n){var r=n(514),o=function(e){var t=/[height|width]$/;return t.test(e)},i=function(e){var t="",n=Object.keys(e);return n.forEach(function(i,a){var s=e[i];i=r(i),o(i)&&"number"==typeof s&&(s+="px"),t+=s===!0?i:s===!1?"not "+i:"("+i+": "+s+")",a<n.length-1&&(t+=" and ")}),t},a=function(e){var t="";return"string"==typeof e?e:e instanceof Array?(e.forEach(function(n,r){t+=i(n),r<e.length-1&&(t+=", ")}),t):i(e)};e.exports=a},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={isAppearSupported:function(e){return e.transitionName&&e.transitionAppear||e.animation.appear},isEnterSupported:function(e){return e.transitionName&&e.transitionEnter||e.animation.enter},isLeaveSupported:function(e){return e.transitionName&&e.transitionLeave||e.animation.leave},allowAppearCallback:function(e){return e.transitionAppear||e.animation.appear},allowEnterCallback:function(e){return e.transitionEnter||e.animation.enter},allowLeaveCallback:function(e){return e.transitionLeave||e.animation.leave}};t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(146),s=r(a),l=n(81),u=r(l),c=n(54),p=r(c),f=n(15),d=r(f),h=i["default"].createClass({displayName:"MonthCalendar",mixins:[p["default"],u["default"]],onKeyDown:function(e){var t=e.keyCode,n=e.ctrlKey||e.metaKey,r=this.state.value,o=r;switch(t){case d["default"].DOWN:o=r.clone(),o.addMonth(3);break;case d["default"].UP:o=r.clone(),o.addMonth(-3);break;case d["default"].LEFT:o=r.clone(),n?o.addYear(-1):o.addMonth(-1);break;case d["default"].RIGHT:o=r.clone(),n?o.addYear(1):o.addMonth(1);break;case d["default"].ENTER:return this.onSelect(r),e.preventDefault(),1;default:return}if(o!==r)return this.setValue(o),e.preventDefault(),1},render:function(){var e=this.props,t=i["default"].createElement(s["default"],{locale:e.locale,disabledDate:e.disabledDate,style:{position:"relative"},value:this.state.value,rootPrefixCls:e.prefixCls,onChange:this.setValue,onSelect:this.onSelect});return this.renderRoot({children:t})}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e,t){this[e]=t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a),l=n(4),u=r(l),c=n(83),p=r(c),f=n(15),d=r(f),h=n(399),y=r(h),v=n(28),m=r(v),g=s["default"].createClass({displayName:"Picker",propTypes:{animation:a.PropTypes.oneOfType([a.PropTypes.func,a.PropTypes.string]),disabled:a.PropTypes.bool,transitionName:a.PropTypes.string,onChange:a.PropTypes.func,onOpen:a.PropTypes.func,onClose:a.PropTypes.func,children:a.PropTypes.func,getCalendarContainer:a.PropTypes.func,calendar:a.PropTypes.element,style:a.PropTypes.object,open:a.PropTypes.bool,defaultOpen:a.PropTypes.bool,prefixCls:a.PropTypes.string,placement:a.PropTypes.any,value:a.PropTypes.oneOfType([a.PropTypes.object,a.PropTypes.array]),defaultValue:a.PropTypes.oneOfType([a.PropTypes.object,a.PropTypes.array]),align:a.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-calendar-picker",style:{},align:{},placement:"bottomLeft",defaultOpen:!1,onChange:o,onOpen:o,onClose:o}},getInitialState:function(){var e=this.props,t=void 0;t="open"in e?e.open:e.defaultOpen;var n=e.value||e.defaultValue;return this.saveCalendarRef=i.bind(this,"calendarInstance"),{open:t,value:n}},componentWillReceiveProps:function(e){var t=e.value,n=e.open;"value"in e&&this.setState({value:t}),void 0!==n&&this.setState({open:n})},onCalendarKeyDown:function(e){e.keyCode===d["default"].ESC&&(e.stopPropagation(),this.close(this.focus))},onCalendarSelect:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=this.props;"value"in n||this.setState({value:e}),("keyboard"===t.source||!n.calendar.props.timePicker&&"dateInput"!==t.source||"todayButton"===t.source)&&this.close(this.focus),n.onChange(e)},onKeyDown:function(e){e.keyCode!==d["default"].DOWN||this.state.open||(this.open(this.focusCalendar),e.preventDefault())},onCalendarOk:function(){this.close(this.focus)},onCalendarClear:function(){this.close(this.focus)},onVisibleChange:function(e){this.setOpen(e,this.focusCalendar)},getCalendarElement:function(){var e=this.props,t=this.state,n=e.calendar,r=t.value,o=void 0;o=Array.isArray(r)?r[0]:r;var i={ref:this.saveCalendarRef,defaultValue:o||n.props.defaultValue,defaultSelectedValue:r,onKeyDown:this.onCalendarKeyDown,onOk:(0,p["default"])(n.props.onOk,this.onCalendarOk),onSelect:(0,p["default"])(n.props.onSelect,this.onCalendarSelect),onClear:(0,p["default"])(n.props.onClear,this.onCalendarClear)};return s["default"].cloneElement(n,i)},setOpen:function(e,t){var n=this.props,r=n.onOpen,o=n.onClose;if(this.state.open!==e){this.setState({open:e},t);var i={open:e};e?r(i):o(i)}},open:function(e){this.setOpen(!0,e)},close:function(e){this.setOpen(!1,e)},focus:function(){this.state.open||u["default"].findDOMNode(this).focus()},focusCalendar:function(){this.state.open&&this.calendarInstance.focus()},render:function(){var e=this.props,t=e.prefixCls,n=e.placement,r=e.style,o=e.getCalendarContainer,i=e.align,a=e.animation,l=e.disabled,u=e.transitionName,c=e.children,p=this.state;return s["default"].createElement(m["default"],{popup:this.getCalendarElement(),popupAlign:i,builtinPlacements:y["default"],popupPlacement:n,action:l&&!p.open?[]:["click"],destroyPopupOnHide:!0,getPopupContainer:o,popupStyle:r,popupAnimation:a,popupTransitionName:u,popupVisible:p.open,onPopupVisibleChange:this.onVisibleChange,prefixCls:t},s["default"].cloneElement(c(p,e),{onKeyDown:this.onKeyDown}))}});t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=this.props.value.clone();t.addMonth(e),this.props.onValueChange(t)}function i(e){var t=this.props.value.clone();t.addYear(e),this.props.onValueChange(t)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a),l=n(146),u=r(l),c=n(19),p=n(148),f=r(p),d=n(170),h=r(d),y=s["default"].createClass({displayName:"CalendarHeader",propTypes:{enablePrev:a.PropTypes.any,enableNext:a.PropTypes.any,prefixCls:a.PropTypes.string,locale:a.PropTypes.object,value:a.PropTypes.object,onValueChange:a.PropTypes.func},getDefaultProps:function(){return{enableNext:1,enablePrev:1}},getInitialState:function(){var e=this.props;return this.yearFormatter=(0,c.getFormatter)(e.locale.yearFormat,e.locale),this.monthFormatter=(0,c.getFormatter)(e.locale.monthFormat,e.locale),this.nextMonth=o.bind(this,1),this.previousMonth=o.bind(this,-1),this.nextYear=i.bind(this,1),this.previousYear=i.bind(this,-1),{}},componentWillReceiveProps:function(e){var t=this.props.locale,n=e.locale;n!==t&&(this.yearFormatter=(0,c.getFormatter)(n.yearFormat,n),this.monthFormatter=(0,c.getFormatter)(n.monthFormat,n))},onSelect:function(e){this.setState({showMonthPanel:0,showYearPanel:0}),this.props.onValueChange(e)},getMonthYearElement:function(){var e=this.props,t=e.prefixCls,n=e.locale,r=this.props.value,o=n.monthBeforeYear,i=t+"-"+(o?"my-select":"ym-select"),a=s["default"].createElement("a",{className:t+"-year-select",role:"button",onClick:this.showYearPanel,title:n.monthSelect},this.yearFormatter.format(r)),l=s["default"].createElement("a",{className:t+"-month-select",role:"button",onClick:this.showMonthPanel,title:n.monthSelect},this.monthFormatter.format(r)),u=[];return u=o?[l,a]:[a,l],s["default"].createElement("span",{className:i},(0,h["default"])(u))},showIf:function(e,t){return e?t:null},showMonthPanel:function(){this.setState({showMonthPanel:1,showYearPanel:0})},showYearPanel:function(){this.setState({showMonthPanel:0,showYearPanel:1})},render:function(){var e=this.props,t=e.enableNext,n=e.enablePrev,r=e.prefixCls,o=e.locale,i=e.value,a=this.state,l=null;a.showMonthPanel?l=u["default"]:a.showYearPanel&&(l=f["default"]);var c=void 0;return l&&(c=s["default"].createElement(l,{locale:o,defaultValue:i,rootPrefixCls:r,onSelect:this.onSelect})),s["default"].createElement("div",{className:r+"-header"},s["default"].createElement("div",{style:{position:"relative"}},this.showIf(n,s["default"].createElement("a",{className:r+"-prev-year-btn",role:"button",onClick:this.previousYear,title:o.previousYear},"\xab")),this.showIf(n,s["default"].createElement("a",{className:r+"-prev-month-btn",role:"button",onClick:this.previousMonth,title:o.previousMonth},"\u2039")),this.getMonthYearElement(),this.showIf(t,s["default"].createElement("a",{className:r+"-next-month-btn",onClick:this.nextMonth,title:o.nextMonth},"\u203a")),this.showIf(t,s["default"].createElement("a",{className:r+"-next-year-btn",onClick:this.nextYear,title:o.nextYear},"\xbb"))),c)}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.prefixCls,n=e.locale,r=e.okDisabled,o=e.onOk,i=t+"-ok-btn";return r&&(i+=" "+t+"-ok-btn-disabled"),a["default"].createElement("a",{className:i,role:"button",onClick:r?null:o},n.ok)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var i=n(1),a=r(i);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.prefixCls,n=e.locale,r=e.value,o=e.timePicker,i=e.disabledDate,l=e.disabledTime,u=e.onToday,c=e.text,p=!1,f=c;!f&&o&&(f=n.now),f=f||n.today;var d="";return i&&(p=!(0,s.isAllowedDate)((0,s.getTodayTime)(r),i,l),p&&(d=t+"-today-btn-disabled")),a["default"].createElement("a",{className:t+"-today-btn "+d,role:"button",onClick:p?null:u,title:(0,s.getTodayTimeStr)(r)},f)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var i=n(1),a=r(i),s=n(19);e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={DATE_ROW_COUNT:6,DATE_COL_COUNT:7},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return t&&(e.setHourOfDay(t.getHourOfDay()),e.setMinutes(t.getMinutes()),e.setSeconds(t.getSeconds())),e}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),s=r(a),l=n(4),u=r(l),c=n(19),p=s["default"].createClass({displayName:"DateInput",propTypes:{prefixCls:a.PropTypes.string,timePicker:a.PropTypes.object,disabledTime:a.PropTypes.any,formatter:a.PropTypes.object,locale:a.PropTypes.object,gregorianCalendarLocale:a.PropTypes.object,disabledDate:a.PropTypes.func,onChange:a.PropTypes.func,onClear:a.PropTypes.func,placeholder:a.PropTypes.string,onSelect:a.PropTypes.func,selectedValue:a.PropTypes.object},getInitialState:function(){var e=this.props.selectedValue;return{str:e&&this.props.formatter.format(e)||"",invalid:!1}},componentWillReceiveProps:function(e){var t=e.selectedValue;this.setState({str:t&&e.formatter.format(t)||"",invalid:!1})},onInputChange:function(e){var t=e.target.value;this.setState({str:t});var n=void 0,r=this.props,i=r.disabledDate,a=r.formatter,s=r.gregorianCalendarLocale,l=r.onChange;if(t){try{n=o(a.parse(t,{locale:s,obeyCount:!0}),this.props.selectedValue)}catch(u){return void this.setState({invalid:!0})}if(!n||i&&i(n))return void this.setState({invalid:!0});var c=this.props.selectedValue;c&&n?c.getTime()!==n.getTime()&&l(n):c!==n&&l(n)}else l(null);this.setState({invalid:!1})},onClear:function(){this.setState({str:""}),this.props.onClear(null)},getRootDOMNode:function(){return u["default"].findDOMNode(this)},focus:function(){this.refs.dateInput.focus()},render:function(){var e=this.props,t=this.state,n=t.invalid,r=t.str,o=e.selectedValue,a=e.locale,l=e.prefixCls,u=e.placeholder,p=e.onChange,f=e.timePicker,d=e.disabledTime,h=e.gregorianCalendarLocale,y=n?l+"-input-invalid":"",v=d&&f?(0,c.getTimeConfig)(o,d):null;return s["default"].createElement("div",{className:l+"-input-wrap"},s["default"].createElement("div",{className:l+"-time-picker-wrap"},f?s["default"].cloneElement(f,i({showClear:!1,allowEmpty:!1,getPopupContainer:this.getRootDOMNode,gregorianCalendarLocale:h,value:o,onChange:p},v)):null),s["default"].createElement("div",{className:l+"-date-input-wrap"},s["default"].createElement("input",{ref:"dateInput",className:l+"-input "+y,value:r,placeholder:u,onChange:this.onInputChange})),e.showClear?s["default"].createElement("a",{className:l+"-clear-btn",role:"button",title:a.clear,onClick:this.onClear}):null)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(390),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(131),i=r(o);t["default"]={today:"\u4eca\u5929",now:"\u6b64\u523b",backToToday:"\u8fd4\u56de\u4eca\u5929",ok:"\u786e\u5b9a",clear:"\u6e05\u9664",month:"\u6708",year:"\u5e74",previousMonth:"\u4e0a\u4e2a\u6708 (\u7ffb\u9875\u4e0a\u952e)",nextMonth:"\u4e0b\u4e2a\u6708 (\u7ffb\u9875\u4e0b\u952e)",monthSelect:"\u9009\u62e9\u6708\u4efd",yearSelect:"\u9009\u62e9\u5e74\u4efd",decadeSelect:"\u9009\u62e9\u5e74\u4ee3",yearFormat:"yyyy'\u5e74'",monthFormat:"M'\u6708'",dateFormat:"yyyy'\u5e74'M'\u6708'd'\u65e5'",previousYear:"\u4e0a\u4e00\u5e74 (Control\u952e\u52a0\u5de6\u65b9\u5411\u952e)",nextYear:"\u4e0b\u4e00\u5e74 (Control\u952e\u52a0\u53f3\u65b9\u5411\u952e)",previousDecade:"\u4e0a\u4e00\u5e74\u4ee3",nextDecade:"\u4e0b\u4e00\u5e74\u4ee3",previousCentury:"\u4e0a\u4e00\u4e16\u7eaa",nextCentury:"\u4e0b\u4e00\u4e16\u7eaa",format:i["default"]},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=this.state.value.clone();t.addYear(e),this.setAndChangeValue(t)}function i(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a),l=n(148),u=r(l),c=n(147),p=r(c),f=s["default"].createClass({displayName:"MonthPanel",propTypes:{onChange:a.PropTypes.func,disabledDate:a.PropTypes.func,onSelect:a.PropTypes.func},getDefaultProps:function(){return{onChange:i,onSelect:i}},getInitialState:function(){var e=this.props;return this.nextYear=o.bind(this,1),this.previousYear=o.bind(this,-1),this.prefixCls=e.rootPrefixCls+"-month-panel",{value:e.value||e.defaultValue}},componentWillReceiveProps:function(e){"value"in e&&this.setState({value:e.value})},onYearPanelSelect:function(e){this.setState({showYearPanel:0}),this.setAndChangeValue(e)},setAndChangeValue:function(e){this.setValue(e),this.props.onChange(e)},setAndSelectValue:function(e){this.setValue(e),this.props.onSelect(e)},setValue:function(e){"value"in this.props||this.setState({value:e})},showYearPanel:function(){this.setState({showYearPanel:1})},render:function(){var e=this.props,t=this.state.value,n=e.locale,r=t.getYear(),o=this.prefixCls,i=void 0;return this.state.showYearPanel&&(i=s["default"].createElement(u["default"],{locale:n,value:t,rootPrefixCls:e.rootPrefixCls,onSelect:this.onYearPanelSelect})),s["default"].createElement("div",{className:o,style:e.style},s["default"].createElement("div",null,s["default"].createElement("div",{className:o+"-header"},s["default"].createElement("a",{className:o+"-prev-year-btn",role:"button",onClick:this.previousYear,title:n.previousYear},"\xab"),s["default"].createElement("a",{className:o+"-year-select",role:"button",onClick:this.showYearPanel,title:n.yearSelect},s["default"].createElement("span",{className:o+"-year-select-content"},r),s["default"].createElement("span",{className:o+"-year-select-arrow"},"x")),s["default"].createElement("a",{className:o+"-next-year-btn",role:"button",onClick:this.nextYear,title:n.nextYear},"\xbb")),s["default"].createElement("div",{className:o+"-body"},s["default"].createElement(p["default"],{disabledDate:e.disabledDate,onSelect:this.setAndSelectValue,locale:n,value:t,prefixCls:o}))),i)}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}function u(e){var t=this.state.value.clone();t.rollSetMonth(e),this.setAndSelectValue(t)}function c(){}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(2),h=r(d),y=4,v=3,m=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return r.state={value:n.value},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value})},t.prototype.getMonths=function(){for(var e=this.props,t=this.state.value,n=t.clone(),r=e.locale,o=[],i=r.format.shortMonths,a=0,s=0;s<y;s++){o[s]=[];for(var l=0;l<v;l++)n.rollSetMonth(a),o[s][l]={value:a,content:i[a],title:i[a]},a++}return o},t.prototype.setAndSelectValue=function(e){this.setState({value:e}),this.props.onSelect(e)},t.prototype.render=function(){var e=this,t=this.props,n=this.state.value,r=n.clone();r.setTime(Date.now());var o=this.getMonths(),a=n.getMonth(),s=t.prefixCls,l=t.locale,c=t.contentRender,p=t.cellRender,d=o.map(function(o,d){var y=o.map(function(o){var d,y=!1;if(t.disabledDate){var v=n.clone();v.rollSetMonth(o.value),y=t.disabledDate(v)}var m=(d={},i(d,s+"-cell",1),i(d,s+"-cell-disabled",y),i(d,s+"-selected-cell",o.value===a),i(d,s+"-current-cell",r.getYear()===n.getYear()&&o.value===r.getMonth()),d),g=void 0;if(p){var b=n.clone();b.rollSetMonth(o.value),g=p(b,l)}else{var P=void 0;if(c){var C=n.clone();C.rollSetMonth(o.value),P=c(C,l)}else P=o.content;g=f["default"].createElement("div",{className:s+"-month"},P)}return f["default"].createElement("td",{role:"gridcell",key:o.value,onClick:y?null:u.bind(e,o.value),title:o.title,className:(0,h["default"])(m)},g)});return f["default"].createElement("tr",{key:d,role:"row"},y)});return f["default"].createElement("table",{className:s+"-table",cellSpacing:"0",role:"grid"},f["default"].createElement("tbody",{className:s+"-tbody"},d))},t}(p.Component);m.defaultProps={onSelect:c},m.propTypes={onSelect:p.PropTypes.func,cellRender:p.PropTypes.func,prefixCls:p.PropTypes.string,value:p.PropTypes.object},t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}function u(e){var t=this.state.value.clone();t.addYear(e),this.setState({value:t})}function c(e){var t=this.state.value.clone();t.setYear(e),t.rollSetMonth(this.state.value.getMonth()),this.props.onSelect(t)}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(2),h=r(d),y=n(396),v=r(y),m=4,g=3,b=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return r.prefixCls=n.rootPrefixCls+"-year-panel",r.state={value:n.value||n.defaultValue},r.nextDecade=u.bind(r,10),r.previousDecade=u.bind(r,-10),["showDecadePanel","onDecadePanelSelect"].forEach(function(e){r[e]=r[e].bind(r)}),r}return l(t,e),t.prototype.onDecadePanelSelect=function(e){this.setState({value:e,showDecadePanel:0})},t.prototype.getYears=function(){for(var e=this.state.value,t=e.getYear(),n=10*parseInt(t/10,10),r=n-1,o=n+9,i=[],a=0,s=0;s<m;s++){i[s]=[];for(var l=0;l<g;l++){var u=r+a,c=void 0;c=u<n?"":u>o?"":String(u),i[s][l]={content:c,year:u,title:c},a++}}return i},t.prototype.showDecadePanel=function(){this.setState({showDecadePanel:1})},t.prototype.render=function(){var e=this,t=this.props,n=this.state.value,r=t.locale,o=this.getYears(),a=n.getYear(),s=10*parseInt(a/10,10),l=s+9,u=this.prefixCls,p=o.map(function(t,n){var r=t.map(function(t){var n,r=(n={},i(n,u+"-cell",1),i(n,u+"-selected-cell",t.year===a),i(n,u+"-last-decade-cell",t.year<s),i(n,u+"-next-decade-cell",t.year>l),n),o=void 0;return o=t.year<s?e.previousDecade:t.year>l?e.nextDecade:c.bind(e,t.year),f["default"].createElement("td",{role:"gridcell",title:t.title,key:t.content,onClick:o,className:(0,h["default"])(r)},f["default"].createElement("a",{className:u+"-year"},t.content))});return f["default"].createElement("tr",{key:n,role:"row"},r)}),d=void 0;return this.state.showDecadePanel&&(d=f["default"].createElement(v["default"],{locale:r,value:n,rootPrefixCls:t.rootPrefixCls,onSelect:this.onDecadePanelSelect})),f["default"].createElement("div",{className:this.prefixCls},f["default"].createElement("div",null,f["default"].createElement("div",{className:u+"-header"},f["default"].createElement("a",{className:u+"-prev-decade-btn",role:"button",onClick:this.previousDecade,title:r.previousDecade},"\xab"),f["default"].createElement("a",{className:u+"-decade-select",role:"button",onClick:this.showDecadePanel,title:r.decadeSelect},f["default"].createElement("span",{className:u+"-decade-select-content"},s,"-",l),f["default"].createElement("span",{className:u+"-decade-select-arrow"},"x")),f["default"].createElement("a",{className:u+"-next-decade-btn",role:"button",onClick:this.nextDecade,title:r.nextDecade},"\xbb")),f["default"].createElement("div",{className:u+"-body"},f["default"].createElement("table",{className:u+"-table",cellSpacing:"0",role:"grid"},f["default"].createElement("tbody",{className:u+"-tbody"},p)))),d)},t}(f["default"].Component);t["default"]=b,b.propTypes={rootPrefixCls:p.PropTypes.string,value:p.PropTypes.object,defaultValue:p.PropTypes.object},b.defaultProps={onSelect:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(404)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){function e(e){var t=f["default"].createClass({displayName:"Form",mixins:n,getInitialState:function(){var e=void 0;return r&&(e=r(this.props)),this.fields=e||{},this.instances={},this.fieldsMeta={},this.cachedBind={},{submitting:!1}},componentWillReceiveProps:function(e){r&&(this.fields=r(e))},onChange:function(e,t){for(var n=e,r=this.getFieldMeta(n),o=r.validate,i=arguments.length,a=Array(i>2?i-2:0),s=2;s<i;s++)a[s-2]=arguments[s];r[t]&&r[t].apply(r,a);var u=r.getValueFromEvent?r.getValueFromEvent.apply(r,a):d.getValueFromEvent.apply(void 0,a),p=void 0,f=(0,d.getNameKeyObj)(n);this.getFieldMeta(f.name).exclusive&&(n=f.name);var h=this.getField(n);p=(0,c["default"])({},h,{value:u,dirty:(0,d.hasRules)(o)}),this.setFields((0,l["default"])({},n,p))},onChangeValidate:function(e,t){for(var n=e,r=this.getFieldMeta(n),o=arguments.length,i=Array(o>2?o-2:0),a=2;a<o;a++)i[a-2]=arguments[a];r[t]&&r[t].apply(r,i);var s=r.getValueFromEvent?r.getValueFromEvent.apply(r,i):d.getValueFromEvent.apply(void 0,i),l=(0,d.getNameKeyObj)(n);this.getFieldMeta(l.name).exclusive&&(n=l.name);var u=this.getField(n);u.value=s,u.dirty=!0,this.validateFieldsInternal([u],{action:t,options:{firstFields:!!r.validateFirst}})},getCacheBind:function(e,t,n){var r=this.cachedBind[e]=this.cachedBind[e]||{};return r[t]||(r[t]=n.bind(this,e,t)),r[t]},getFieldMeta:function(e){return this.fieldsMeta[e]},getField:function(e){var t=this.fields;return(0,c["default"])({},t[e],{name:e})},getFieldProps:function(e){function t(e){return e.trigger.indexOf(l)===-1||!e.rules||!e.rules.length}var n=this,r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];if(!e)throw new Error("must call getFieldProps with valid name string!");var o=r.rules,a=r.trigger,l=void 0===a?m:a,u=r.valuePropName,p=void 0===u?"value":u,f=r.getValueProps,h=r.exclusive,y=r.validateTrigger,b=void 0===y?v:y,P=r.validate,C=void 0===P?[]:P,T=(0,d.getNameKeyObj)(e),O=T.name,w=T.key,x=this.fieldsMeta,E=void 0,S=x[O];w?(S=x[O]=x[O]||{},S.virtual=!h,S.hidden=!h,S.exclusive=h,E=x[e]=x[e]||{}):E=x[e]=x[e]||{},"initialValue"in r&&(E.initialValue=r.initialValue);var k={};w&&(k.key=w),i&&(k[i]=e);var N=C.map(function(e){var t=(0,c["default"])({},e,{trigger:e.trigger||[]});return"string"==typeof t.trigger&&(t.trigger=[t.trigger]),t});o&&N.push({trigger:b?[].concat(b):[],rules:o}),N.filter(function(e){return!!e.rules&&e.rules.length}).map(function(e){return e.trigger}).reduce(function(e,t){return e.concat(t)},[]).forEach(function(t){k[t]=n.getCacheBind(e,t,n.onChangeValidate)}),l&&N.every(t)&&(k[l]=this.getCacheBind(e,l,this.onChange));var j=h?this.getField(O):this.getField(e),_=g;j&&"value"in j&&(_=j.value),_===g&&(_=h?x[O].initialValue:E.initialValue),f?k=(0,c["default"])({},k,f(_)):k[p]=_,k.ref=this.getCacheBind(e,e+"__ref",this.saveRef);var M=(0,c["default"])({},E,r,{validate:N});return x[e]=M,s&&(k[s]=M),k},getFieldMember:function(e,t){var n=this.getField(e);return n&&n[t]},getFieldError:function(e){return(0,d.getErrorStrs)(this.getFieldMember(e,"errors"))},getValidFieldsName:function(){var e=this.fieldsMeta;return e?(0,a["default"])(e).filter(function(t){return!e[t].hidden}):[]},getFieldsValue:function(e){var t=this,n=e||(0,d.flatFieldNames)(this.getValidFieldsName()),r={};return n.forEach(function(e){r[e]=t.getFieldValue(e)}),r},getFieldValue:function(e){var t=this.fields;return this.getValueFromFields(e,t)},getFieldInstance:function(e){return this.instances[e]},getValueFromFieldsInternal:function(e,t){var n=t[e];if(n&&"value"in n)return n.value;var r=this.fieldsMeta[e];return r&&r.initialValue},getValueFromFields:function(e,t){var n=this.fieldsMeta;if(n[e]&&n[e].virtual){var r={};for(var o in n)if(n.hasOwnProperty(o)){var i=(0,d.getNameKeyObj)(o);i.name===e&&i.key&&(r[i.key]=this.getValueFromFieldsInternal(o,t))}return r}return this.getValueFromFieldsInternal(e,t)},getRules:function(e,t){var n=e.validate.filter(function(e){return!t||e.trigger.indexOf(t)>=0}).map(function(e){return e.rules});return(0,d.flattenArray)(n)},setFields:function(e){var t=this,n=this.fieldsMeta,r=e,i=(0,c["default"])({},this.fields,r),s={};(0,a["default"])(n).forEach(function(e){var r=(0,d.getNameKeyObj)(e),o=r.name,a=r.key;a&&n[o].exclusive||(s[e]=t.getValueFromFields(e,i))});var l=(0,a["default"])(r);(0,a["default"])(s).forEach(function(e){var r=s[e],o=n[e];if(o&&o.normalize){var a=o.normalize(r,t.getValueFromFields(e,t.fields),s);a!==r&&(i[e]=(0,c["default"])({},i[e],{value:a}))}}),this.fields=i,o&&!function(){var e={};l.forEach(function(n){e[n]=t.getField(n)}),o(t.props,e)}(),this.forceUpdate()},setFieldsValue:function(e){var t={},n=this.fieldsMeta,r=this.fields;for(var o in e)if(e.hasOwnProperty(o)){var i=e[o];if(n[o]&&n[o].virtual){(0,d.clearVirtualField)(o,r,n);for(var a in i)i.hasOwnProperty(a)&&(t[(0,d.getNameKeyStr)(o,a)]=i[a])}else t[o]={name:o,value:i}}this.setFields(t)},setFieldsInitialValue:function(e){var t=this.fieldsMeta;for(var n in e)if(e.hasOwnProperty(n)){var r=t[n];t[n]=(0,c["default"])({},r,{initialValue:e[n]})}},saveRef:function(e,t,n){if(!n)return delete this.fieldsMeta[e],delete this.fields[e],delete this.instances[e],void delete this.cachedBind[e];var r=this.getFieldMeta(e);if(r&&r.ref){if("string"==typeof r.ref)throw new Error("can not set ref string for "+e);r.ref(n)}this.instances[e]=n},validateFieldsInternal:function(e,t,n){var r=this,o=t.fieldNames,i=t.action,s=t.options,l=void 0===s?{}:s,p={},f={},h={},v={};if(e.forEach(function(e){var t=e.name;if(l.force!==!0&&e.dirty===!1)return void(e.errors&&(v[t]={errors:e.errors}));var n=r.getFieldMeta(t),o=(0,c["default"])({},e);o.errors=void 0,o.validating=!0,o.dirty=!0,p[t]=r.getRules(n,i),f[t]=o.value,h[t]=o}),this.setFields(h),(0,a["default"])(f).forEach(function(e){f[e]=r.getFieldValue(e)}),n&&(0,d.isEmptyObject)(h))return void n((0,d.isEmptyObject)(v)?null:v,this.getFieldsValue((0,d.flatFieldNames)(o)));var m=new y["default"](p);u&&m.messages(u),m.validate(f,l,function(e){var t=(0, c["default"])({},v);e&&e.length&&e.forEach(function(e){var n=e.field;t[n]||(t[n]={errors:[]});var r=t[n].errors;r.push(e)});var i=[],s={};(0,a["default"])(p).forEach(function(e){var n=t[e],o=r.getField(e);o.value!==f[e]?i.push({name:e}):(o.errors=n&&n.errors,o.value=f[e],o.validating=!1,o.dirty=!1,s[e]=o)}),r.setFields(s),n&&(i.length&&i.forEach(function(e){var n=e.name,r=[{message:n+" need to revalidate",field:n}];t[n]={expired:!0,errors:r}}),n((0,d.isEmptyObject)(t)?null:t,r.getFieldsValue((0,d.flatFieldNames)(o))))})},validateFields:function(e,t,n){var r=this,o=(0,d.getParams)(e,t,n),i=o.names,a=o.callback,s=o.options,l=i||this.getValidFieldsName(),u=l.map(function(e){var t=r.getFieldMeta(e);if(!(0,d.hasRules)(t.validate))return null;var n=r.getField(e);return n.value=r.getFieldValue(e),n}).filter(function(e){return!!e});return u.length?("firstFields"in s||(s.firstFields=l.filter(function(e){var t=r.getFieldMeta(e);return!!t.validateFirst})),void this.validateFieldsInternal(u,{fieldNames:l,options:s},a)):void(a&&a(null,this.getFieldsValue((0,d.flatFieldNames)(l))))},isFieldValidating:function(e){return this.getFieldMember(e,"validating")},isFieldsValidating:function(e){var t=this,n=e||this.getValidFieldsName();return n.some(function(e){return t.isFieldValidating(e)})},isSubmitting:function(){return this.state.submitting},submit:function(e){var t=this,n=function(){t.setState({submitting:!1})};this.setState({submitting:!0}),e(n)},resetFields:function(e){var t={},n=this.fields,r=!1,o=e||(0,a["default"])(n);o.forEach(function(e){var o=n[e];o&&"value"in o&&(r=!0,t[e]={})}),r&&this.setFields(t)},render:function(){var t=(0,l["default"])({},P,this.getForm());C&&(t.ref="wrappedComponent");var n=h.call(this,(0,c["default"])({},t,this.props));return f["default"].createElement(e,n)}});return(0,d.argumentContainer)(t,e)}var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?[]:arguments[1],r=t.mapPropsToFields,o=t.onFieldsChange,i=t.fieldNameProp,s=t.fieldMetaProp,u=t.validateMessages,p=t.mapProps,h=void 0===p?d.mirror:p,b=t.formPropName,P=void 0===b?"form":b,C=t.withRef;return e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(116),a=r(i),s=n(12),l=r(s),u=n(7),c=r(u),p=n(1),f=r(p),d=n(151),h=n(179),y=r(h),v="onChange",m=v,g={};t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return e.displayName||e.name||"WrappedComponent"}function i(e,t){return e.displayName="Form("+o(t)+")",e.WrappedComponent=t,(0,w["default"])(e,t)}function a(e){if(!e||!e.target)return e;var t=e.target;return"checkbox"===t.type?t.checked:t.value}function s(e){return e?e.map(function(e){return e&&e.message?e.message:e}):e}function l(e){return 0===(0,T["default"])(e).length}function u(e){return Array.prototype.concat.apply([],e)}function c(e){return e}function p(e){return!!e&&e.some(function(e){return!!e.rules&&e.rules.length})}function f(e,t){return 0===e.lastIndexOf(t,0)}function d(e,t,n){var r=e,o=n,i=t;return void 0===n&&("function"==typeof r?(o=r,i={},r=void 0):Array.isArray(e)?"function"==typeof i?(o=i,i={}):i=i||{}:(o=i,i=r||{},r=void 0)),{names:r,callback:o,options:i}}function h(e,t){return t?""+e+x+t:e}function y(e){var t=e.indexOf(x);if(e.indexOf(x)!==-1){var n=e.slice(0,t),r=e.slice(t+x.length);return{name:n,key:r}}return{name:e}}function v(e,t){var n=(0,P["default"])({},e);return(0,T["default"])(n).forEach(function(e){if(t[e]&&t[e].virtual){var r=n[e];for(var o in r)r.hasOwnProperty(o)&&(n[h(e,o)]=r[o]);delete n[e]}}),n}function m(e){var t={};return e.forEach(function(e){t[y(e).name]=1}),(0,T["default"])(t)}function g(e,t,n){n[e]&&n[e].virtual&&(0,T["default"])(t).forEach(function(n){y(n).name===e&&delete t[n]})}Object.defineProperty(t,"__esModule",{value:!0});var b=n(7),P=r(b),C=n(116),T=r(C);t.argumentContainer=i,t.getValueFromEvent=a,t.getErrorStrs=s,t.isEmptyObject=l,t.flattenArray=u,t.mirror=c,t.hasRules=p,t.startsWith=f,t.getParams=d,t.getNameKeyStr=h,t.getNameKeyObj=y,t.flatFields=v,t.flatFieldNames=m,t.clearVirtualField=g;var O=n(376),w=r(O),x="."},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){return!e.length||e.every(function(e){return!!e.props.disabled})}function a(e,t){var n=t,r=e.children,o=e.eventKey;if(n){var i=void 0;if((0,O.loopMenuItem)(r,function(e,t){e.props.disabled||n!==(0,O.getKeyFromChildrenIndex)(e,o,t)||(i=!0)}),i)return n}return n=null,e.defaultActiveFirst?((0,O.loopMenuItem)(r,function(e,t){n||e.props.disabled||(n=(0,O.getKeyFromChildrenIndex)(e,o,t))}),n):n}function s(e,t,n){n&&(void 0!==t?(this.instanceArray[e]=this.instanceArray[e]||[],this.instanceArray[e][t]=n):this.instanceArray[e]=n)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(1),c=r(u),p=n(4),f=r(p),d=n(15),h=r(d),y=n(83),v=r(y),m=n(2),g=r(m),b=n(78),P=r(b),C=n(10),T=r(C),O=n(55),w=n(421),x=r(w),E={propTypes:{focusable:u.PropTypes.bool,multiple:u.PropTypes.bool,style:u.PropTypes.object,defaultActiveFirst:u.PropTypes.bool,visible:u.PropTypes.bool,activeKey:u.PropTypes.string,selectedKeys:u.PropTypes.arrayOf(u.PropTypes.string),defaultSelectedKeys:u.PropTypes.arrayOf(u.PropTypes.string),defaultOpenKeys:u.PropTypes.arrayOf(u.PropTypes.string),openKeys:u.PropTypes.arrayOf(u.PropTypes.string),children:u.PropTypes.any},getDefaultProps:function(){return{prefixCls:"rc-menu",className:"",mode:"vertical",level:1,inlineIndent:24,visible:!0,focusable:!0,style:{}}},getInitialState:function(){var e=this.props;return{activeKey:a(e,e.activeKey)}},componentWillReceiveProps:function(e){var t=void 0;if("activeKey"in e)t={activeKey:a(e,e.activeKey)};else{var n=this.state.activeKey,r=a(e,n);r!==n&&(t={activeKey:r})}t&&this.setState(t)},shouldComponentUpdate:function(e){return this.props.visible||e.visible},componentWillMount:function(){this.instanceArray=[]},onKeyDown:function(e){var t=this,n=e.keyCode,r=void 0;if(this.getFlatInstanceArray().forEach(function(t){t&&t.props.active&&(r=t.onKeyDown(e))}),r)return 1;var o=null;return n!==h["default"].UP&&n!==h["default"].DOWN||(o=this.step(n===h["default"].UP?-1:1)),o?(e.preventDefault(),this.setState({activeKey:o.props.eventKey},function(){(0,P["default"])(f["default"].findDOMNode(o),f["default"].findDOMNode(t),{onlyScrollIfNeeded:!0})}),1):void 0===o?(e.preventDefault(),this.setState({activeKey:null}),1):void 0},onCommonItemHover:function(e){var t=this.props.mode,n=e.key,r=e.hover,o=e.trigger,i=this.state.activeKey;if(o&&!r&&!this.props.closeSubMenuOnMouseLeave&&e.item.isSubMenu&&"inline"!==t||this.setState({activeKey:r?n:null}),r&&"inline"!==t){var a=this.getFlatInstanceArray().filter(function(e){return e&&e.props.eventKey===i})[0];a&&a.isSubMenu&&a.props.eventKey!==n&&this.onOpenChange({item:a,key:a.props.eventKey,open:!1})}},getFlatInstanceArray:function(){var e=this.instanceArray,t=e.some(function(e){return Array.isArray(e)});return t&&(e=[],this.instanceArray.forEach(function(t){Array.isArray(t)?e.push.apply(e,t):e.push(t)}),this.instanceArray=e),e},renderCommonMenuItem:function(e,t,n,r){var o=this.state,i=this.props,a=(0,O.getKeyFromChildrenIndex)(e,i.eventKey,t),l=e.props,u=a===o.activeKey,p=(0,T["default"])({mode:i.mode,level:i.level,inlineIndent:i.inlineIndent,renderMenuItem:this.renderMenuItem,rootPrefixCls:i.prefixCls,index:t,parentMenu:this,ref:l.disabled?void 0:(0,v["default"])(e.ref,s.bind(this,t,n)),eventKey:a,closeSubMenuOnMouseLeave:i.closeSubMenuOnMouseLeave,onItemHover:this.onItemHover,active:!l.disabled&&u,multiple:i.multiple,onClick:this.onClick,openTransitionName:this.getOpenTransitionName(),openAnimation:i.openAnimation,onOpenChange:this.onOpenChange,onDeselect:this.onDeselect,onDestroy:this.onDestroy,onSelect:this.onSelect},r);return"inline"===i.mode&&(p.closeSubMenuOnMouseLeave=p.openSubMenuOnMouseEnter=!1),c["default"].cloneElement(e,p)},renderRoot:function(e){var t;this.instanceArray=[];var n=(t={},o(t,e.prefixCls,1),o(t,e.prefixCls+"-"+e.mode,1),o(t,e.className,!!e.className),t),r={className:(0,g["default"])(n),role:"menu","aria-activedescendant":""};return e.id&&(r.id=e.id),e.focusable&&(r.tabIndex="0",r.onKeyDown=this.onKeyDown),c["default"].createElement(x["default"],l({style:e.style,tag:"ul",hiddenClassName:e.prefixCls+"-hidden",visible:e.visible},r),c["default"].Children.map(e.children,this.renderMenuItem))},step:function(e){var t=this.getFlatInstanceArray(),n=this.state.activeKey,r=t.length;if(!r)return null;e<0&&(t=t.concat().reverse());var o=-1;if(t.every(function(e,t){return!e||e.props.eventKey!==n||(o=t,!1)}),this.props.defaultActiveFirst||o===-1||!i(t.slice(o,r-1)))for(var a=(o+1)%r,s=a;;){var l=t[s];if(l&&!l.props.disabled)return l;if(s=(s+1+r)%r,s===a)return null}}};t["default"]=E,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(430),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t){"use strict";e.exports={ZERO:48,NINE:57,NUMPAD_ZERO:96,NUMPAD_NINE:105,BACKSPACE:8,DELETE:46,ENTER:13,ARROW_UP:38,ARROW_DOWN:40}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={items_per_page:"\u6761/\u9875",jump_to:"\u8df3\u81f3",page:"\u9875",prev_page:"\u4e0a\u4e00\u9875",next_page:"\u4e0b\u4e00\u9875",prev_5:"\u5411\u524d 5 \u9875",next_5:"\u5411\u540e 5 \u9875"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(46),i=r(o),a=n(48),s=r(a),l=n(47),u=r(l),c=n(1),p=r(c),f=function(e){function t(){return(0,i["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t}(p["default"].Component);f.propTypes={value:p["default"].PropTypes.string},t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(41),s=r(a),l=i["default"].createClass({displayName:"ExpandIcon",propTypes:{record:o.PropTypes.object,prefixCls:o.PropTypes.string,expandable:o.PropTypes.any,expanded:o.PropTypes.bool,needIndentSpaced:o.PropTypes.bool,onExpand:o.PropTypes.func},shouldComponentUpdate:function(e){return!(0,s["default"])(e,this.props)},render:function(){var e=this.props,t=e.expandable,n=e.prefixCls,r=e.onExpand,o=e.needIndentSpaced,a=e.expanded,s=e.record;if(t){var l=a?"expanded":"collapsed";return i["default"].createElement("span",{className:n+"-expand-icon "+n+"-"+l,onClick:function(e){return r(!a,s,e)}})}return o?i["default"].createElement("span",{className:n+"-expand-icon "+n+"-spaced"}):null}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(12),i=r(o),a=n(1),s=r(a),l=n(2),u=r(l),c=s["default"].createClass({displayName:"TabPane",propTypes:{active:a.PropTypes.bool},render:function(){var e,t=this.props;if(this._isActived=this._isActived||t.active,!this._isActived)return null;var n=t.rootPrefixCls+"-tabpane",r=(0,u["default"])((e={},(0,i["default"])(e,n+"-hidden",!t.active),(0,i["default"])(e,n,1),e));return s["default"].createElement("div",{role:"tabpanel","aria-hidden":t.active?"false":"true",className:r},t.children)}});t["default"]=c,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function r(e){var t=void 0,r=void 0,o=void 0,i=e.ownerDocument,a=i.body,s=i&&i.documentElement;t=e.getBoundingClientRect(),r=t.left,o=t.top,r-=s.clientLeft||a.clientLeft||0,o-=s.clientTop||a.clientTop||0;var l=i.defaultView||i.parentWindow;return r+=n(l),o+=n(l,!0),{left:r,top:o}}function o(){if(!window.getComputedStyle)return!1;if(void 0!==i)return i;var e=document.createElement("p"),t=void 0,n={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var r in n)void 0!==e.style[r]&&(e.style[r]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(n[r]),void 0!==t&&t.length>0&&"none"!==t&&(i=r));return document.body.removeChild(e),i}Object.defineProperty(t,"__esModule",{value:!0}),t.getScroll=n,t.offset=r,t.getTransformPropertyName=o;var i=void 0},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e,t){this[e]=t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a),l=n(28),u=r(l),c=n(479),p=r(c),f=n(482),d=r(f),h=n(161),y=r(h),v=n(481),m=s["default"].createClass({displayName:"Picker",propTypes:{prefixCls:a.PropTypes.string,locale:a.PropTypes.object,value:a.PropTypes.object,disabled:a.PropTypes.bool,allowEmpty:a.PropTypes.bool,defaultValue:a.PropTypes.object,open:a.PropTypes.bool,defaultOpen:a.PropTypes.bool,align:a.PropTypes.object,placement:a.PropTypes.any,transitionName:a.PropTypes.string,getPopupContainer:a.PropTypes.func,placeholder:a.PropTypes.string,formatter:a.PropTypes.any,showHour:a.PropTypes.bool,style:a.PropTypes.object,className:a.PropTypes.string,showSecond:a.PropTypes.bool,disabledHours:a.PropTypes.func,disabledMinutes:a.PropTypes.func,disabledSeconds:a.PropTypes.func,hideDisabledOptions:a.PropTypes.bool,onChange:a.PropTypes.func,onOpen:a.PropTypes.func,onClose:a.PropTypes.func},mixins:[y["default"]],getDefaultProps:function(){return{prefixCls:"rc-time-picker",defaultOpen:!1,style:{},className:"",align:{},allowEmpty:!0,showHour:!0,showSecond:!0,disabledHours:o,disabledMinutes:o,disabledSeconds:o,hideDisabledOptions:!1,placement:"bottomLeft",onChange:o,onOpen:o,onClose:o}},getInitialState:function(){this.savePanelRef=i.bind(this,"panelInstance");var e=this.props,t=e.defaultOpen,n=e.defaultValue,r=e.open,o=void 0===r?t:r,a=e.value,s=void 0===a?n:a;return{open:o,value:s}},componentWillReceiveProps:function(e){var t=e.value,n=e.open;"value"in e&&this.setState({value:t}),void 0!==n&&this.setState({open:n})},onPanelChange:function(e){this.setValue(e)},onPanelClear:function(){this.setValue(null),this.setOpen(!1)},onVisibleChange:function(e){this.setOpen(e)},onEsc:function(){this.setOpen(!1),this.refs.picker.focus()},onKeyDown:function(e){40===e.keyCode&&this.setOpen(!0)},setValue:function(e){"value"in this.props||this.setState({value:e}),this.props.onChange(e)},getFormatter:function(){var e=this.props.formatter,t=this.props.locale;return e?e===this.lastFormatter?this.normalFormatter:(this.normalFormatter=(0,v.getFormatter)(e,t),this.lastFormatter=e,this.normalFormatter):this.props.showSecond?this.props.showHour?(this.normalFormatter||(this.normalFormatter=(0,v.getFormatter)("HH:mm:ss",t)),this.normalFormatter):(this.notShowHourFormatter||(this.notShowHourFormatter=(0,v.getFormatter)("mm:ss",t)),this.notShowHourFormatter):(this.notShowSecondFormatter||(this.notShowSecondFormatter=(0,v.getFormatter)("HH:mm",t)),this.notShowSecondFormatter)},getPanelElement:function(){var e=this.props,t=e.prefixCls,n=e.defaultValue,r=e.locale,o=e.placeholder,i=e.disabledHours,a=e.disabledMinutes,l=e.disabledSeconds,u=e.hideDisabledOptions,c=e.allowEmpty,f=e.showHour,d=e.showSecond;return s["default"].createElement(p["default"],{prefixCls:t+"-panel",ref:this.savePanelRef,value:this.state.value,onChange:this.onPanelChange,gregorianCalendarLocale:r.calendar,onClear:this.onPanelClear,defaultValue:n,showHour:f,onEsc:this.onEsc,showSecond:d,locale:r,allowEmpty:c,formatter:this.getFormatter(),placeholder:o,disabledHours:i,disabledMinutes:a,disabledSeconds:l,hideDisabledOptions:u})},setOpen:function(e,t){var n=this.props,r=n.onOpen,o=n.onClose;if(this.state.open!==e){this.setState({open:e},t);var i={open:e};e?r(i):o(i)}},render:function(){var e=this.props,t=e.prefixCls,n=e.placeholder,r=e.placement,o=e.align,i=e.disabled,a=e.transitionName,l=e.style,c=e.className,p=e.showHour,f=e.showSecond,h=e.getPopupContainer,y=this.state,v=y.open,m=y.value,g=void 0;return p&&f||(g=t+"-panel-narrow"),s["default"].createElement(u["default"],{prefixCls:t+"-panel",popupClassName:g,popup:this.getPanelElement(),popupAlign:o,builtinPlacements:d["default"],popupPlacement:r,action:i?[]:["click"],destroyPopupOnHide:!0,getPopupContainer:h,popupTransitionName:a,popupVisible:v,onPopupVisibleChange:this.onVisibleChange},s["default"].createElement("span",{className:t+" "+c,style:l},s["default"].createElement("input",{className:t+"-input",ref:"picker",type:"text",placeholder:n,readOnly:!0,onKeyDown:this.onKeyDown,disabled:i,value:m&&this.getFormatter().format(m)||""}),s["default"].createElement("span",{className:t+"-icon"})))}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=n(475),a=r(i);t["default"]={propTypes:{prefixCls:o.PropTypes.string,locale:o.PropTypes.object},getDefaultProps:function(){return{locale:a["default"]}}},e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(484)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o=t.placements={left:{points:["cr","cl"],overflow:n,offset:[-4,0],targetOffset:r},right:{points:["cl","cr"],overflow:n,offset:[4,0],targetOffset:r},top:{points:["bc","tc"],overflow:n,offset:[0,-4],targetOffset:r},bottom:{points:["tc","bc"],overflow:n,offset:[0,4],targetOffset:r},topLeft:{points:["bl","tl"],overflow:n,offset:[0,-4],targetOffset:r},leftTop:{points:["tr","tl"],overflow:n,offset:[-4,0],targetOffset:r},topRight:{points:["br","tr"],overflow:n,offset:[0,-4],targetOffset:r},rightTop:{points:["tl","tr"],overflow:n,offset:[4,0],targetOffset:r},bottomRight:{points:["tr","br"],overflow:n,offset:[0,4],targetOffset:r},rightBottom:{points:["bl","br"],overflow:n,offset:[4,0],targetOffset:r},bottomLeft:{points:["tl","bl"],overflow:n,offset:[0,4],targetOffset:r},leftBottom:{points:["br","bl"],overflow:n,offset:[-4,0],targetOffset:r}};t["default"]=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t}(u["default"].Component);t["default"]=c,c.propTypes={value:u["default"].PropTypes.string},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e){var t=e.props;if("value"in t)return t.value;if(e.key)return e.key;throw new Error("no key or value for "+e)}function s(e,t){return"value"===t?a(e):e.props[t]}function l(e){return e.combobox}function u(e){return e.multiple||e.tags||e.treeCheckable}function c(e){return u(e)||l(e)}function p(e){return!c(e)}function f(e){var t=e;return void 0===e?t=[]:Array.isArray(e)||(t=[e]),t}function d(e){e.preventDefault()}function h(e){var t=e;return"label"===t&&(t="title"),t}function y(e,t){return e.every(function(e,n){return e===t[n]})}function v(e){var t=1;return Array.isArray(e)&&(t=e.length),t}function m(e,t,n){return 1===t?(n.first=!0,n.last=!0):(n.first=0===e,n.last=e===t-1),n}function g(e,t,n){var r=function o(e,n,r){var i=v(e);D["default"].Children.forEach(e,function(e,a){var s=n+"-"+a;e&&e.props.children&&e.type&&o(e.props.children,s,{node:e,pos:s}),e&&t(e,a,s,e.key||s,m(a,i,{}),r)})};r(e,0,n)}function b(e){if(!e.length)return e;var t=[],n={};e.forEach(function(e){if(e.pos){var t=e.pos.split("-").length;n[t]||(n[t]=[]),n[t].push(e)}});var r=Object.keys(n).sort(function(e,t){return t-e});return r.reduce(function(e,r){return r&&r!==e&&n[e].forEach(function(e){var o=!1;n[r].forEach(function(t){y(t.pos.split("-"),e.pos.split("-"))&&(o=!0,t.children||(t.children=[]),t.children.push(e))}),o||t.push(e)}),r}),n[r[r.length-1]].concat(t)}function P(e){var t={};e.forEach(function(e){var n=e.split("-").length;t[n]||(t[n]=[]),t[n].push(e)});for(var n=Object.keys(t).sort(),r=function(e){n[e+1]&&t[n[e]].forEach(function(r){for(var o=function(e){t[n[e]].forEach(function(o,i){y(r.split("-"),o.split("-"))&&(t[n[e]][i]=null)}),t[n[e]]=t[n[e]].filter(function(e){return e})},i=e+1;i<n.length;i++)o(i)})},o=0;o<n.length;o++)r(o);var i=[];return n.forEach(function(e){i=i.concat(t[e])}),i}function C(e){var t=e.match(/(.+)(-[^-]+)$/),n="";return t&&3===t.length&&(n=t[1]),n}function T(e){return e.split("-")}function O(e,t,n){var r=Object.keys(e);r.forEach(function(o,i){var a=T(o),s=!1;t.forEach(function(t){var l=T(t);a.length>l.length&&y(l,a)&&(e[o].halfChecked=!1,e[o].checked=n,r[i]=null),a[0]===l[0]&&a[1]===l[1]&&(s=!0)}),s||(r[i]=null)}),r=r.filter(function(e){return e});for(var o=function(n){var o=function a(o){var i=T(o).length;if(!(i<=2)){var s=0,l=0,u=C(o);r.forEach(function(r){var o=T(r);if(o.length===i&&y(T(u),o))if(s++,e[r].checked){l++;var a=t.indexOf(r);a>-1&&(t.splice(a,1),a<=n&&n--)}else e[r].halfChecked&&(l+=.5)});var c=e[u];0===l?(c.checked=!1,c.halfChecked=!1):l===s?(c.checked=!0,c.halfChecked=!1):(c.halfChecked=!0,c.checked=!1),a(u)}};o(t[n],n),i=n},i=0;i<t.length;i++)o(i)}function w(e,t){var n=[],r=[],o=[];return Object.keys(e).forEach(function(t){var i=e[t];i.checked?(r.push(i.key),o.push(_({},i,{pos:t}))):i.halfChecked&&n.push(i.key)}),{halfCheckedKeys:n,checkedKeys:r,checkedNodes:o,treeNodesStates:e,checkedPositions:t}}function x(e,t){var n=[],r={};return g(e,function(e,o,i,s,l){r[i]={node:e,key:s,checked:!1,halfChecked:!1,siblingPosition:l},t.indexOf(a(e))!==-1&&(r[i].checked=!0,n.push(i))}),O(r,P(n.sort()),!0),w(r,n)}function E(e){var t=arguments.length<=1||void 0===arguments[1]?function(e){return e}:arguments[1];return Array.from(e).map(function(e){var n=t(e);return n&&n.props&&n.props.children?D["default"].cloneElement(n,{},E(n.props.children,t)):n})}function S(e){var t=arguments.length<=1||void 0===arguments[1]?0:arguments[1];return D["default"].Children.map(e,function(e,n){var r=t+"-"+n,o={title:e.props.title,label:e.props.label||e.props.title,value:e.props.value,key:e.key,_pos:r};return e.props.children&&(o.children=S(e.props.children,r)),o})}function k(e,t){e.forEach(function(e){t(e),e.children&&k(e.children,t)})}function N(e,t){function n(e){e.forEach(function(e){if(!e.__checked){var t=o.indexOf(e.value),r=e.children;t>-1?(e.__checked=!0,s.push({node:e,pos:e._pos}),o.splice(t,1),r&&k(r,function(e){e.__checked=!0,s.push({node:e,pos:e._pos})})):r&&n(r)}})}function r(e){var t=arguments.length<=1||void 0===arguments[1]?{root:!0}:arguments[1],n=0;e.forEach(function(e){var t=e.children;if(!t||e.__checked||e.__halfChecked)e.__checked?n++:e.__halfChecked&&(n+=.5);else{var o=r(t,e);o.__checked?n++:o.__halfChecked&&(n+=.5)}});var o=e.length;return n===o?(t.__checked=!0,s.push({node:t,pos:t._pos})):n<o&&n>0&&(t.__halfChecked=!0),t.root?e:t}var o=[].concat(i(e));if(!o.length)return o;var a=S(t),s=[];return n(a),r(a),s.forEach(function(e,t){delete s[t].node.__checked,delete s[t].node._pos,s[t].node.props={title:s[t].node.title,label:s[t].node.label||s[t].node.title,value:s[t].node.value},s[t].node.children&&(s[t].node.props.children=s[t].node.children),delete s[t].node.title,delete s[t].node.label,delete s[t].node.value,delete s[t].node.children}),s}function j(e,t){function n(e){for(var r=arguments.length<=1||void 0===arguments[1]?o({},t.id,t.rootPId):arguments[1],i=[],a=0;a<e.length;a++)e[a]=_({},e[a]),e[a][t.pId]===r[t.id]&&(e[a].key=e[a][t.id],i.push(e[a]),e.splice(a--,1));if(i.length&&(r.children=i,i.forEach(function(t){return n(e,t)})),r[t.id]===t.rootPId)return i}return n(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.UNSELECTABLE_ATTRIBUTE=t.UNSELECTABLE_STYLE=void 0;var _=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.getValuePropValue=a,t.getPropValue=s,t.isCombobox=l,t.isMultipleOrTags=u,t.isMultipleOrTagsOrCombobox=c,t.isSingleMode=p,t.toArray=f,t.preventDefaultEvent=d,t.labelCompatible=h,t.isInclude=y,t.loopAllChildren=g,t.flatToHierarchy=b,t.filterParentPosition=P,t.handleCheckState=O,t.getTreeNodesStates=x,t.recursiveCloneChildren=E,t.filterAllCheckedData=N,t.processSimpleTreeData=j;var M=n(1),D=r(M);t.UNSELECTABLE_STYLE={userSelect:"none",WebkitUserSelect:"none"},t.UNSELECTABLE_ATTRIBUTE={unselectable:"unselectable"}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(488),i=r(o),a=n(489),s=r(a);i["default"].TreeNode=s["default"],t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=void 0,n=e.userAgent,r=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];return/trident/i.test(r[1])?(t=/\brv[ :]+(\d+)/g.exec(n)||[],"IE "+(t[1]||"")):"Chrome"===r[1]&&(t=n.match(/\b(OPR|Edge)\/(\d+)/))?t.slice(1).join(" ").replace("OPR","Opera"):(r=r[2]?[r[1],r[2]]:[e.appName,e.appVersion,"-?"],t=n.match(/version\/(\d+)/i),t&&r.splice(1,1,t[1]),r.join(" "))}function i(e){var t=void 0,n=void 0,r=void 0,o=void 0;return e.getClientRects().length?(o=e.getBoundingClientRect(),o.width||o.height?(t=e.ownerDocument,n=t.defaultView,r=t.documentElement,{top:o.top+n.pageYOffset-r.clientTop,left:o.left+n.pageXOffset-r.clientLeft}):o):{top:0,left:0}}function a(e){var t=1;return Array.isArray(e)&&(t=e.length),t}function s(e,t,n){return 1===t?(n.first=!0,n.last=!0):(n.first=0===e,n.last=e===t-1),n}function l(e,t,n){var r=function o(e,n,r){var i=a(e);g["default"].Children.forEach(e,function(e,a){var l=n+"-"+a;e.props.children&&e.type&&e.type.isTreeNode&&o(e.props.children,l,{node:e,pos:l}),t(e,a,l,e.key||l,s(a,i,{}),r)})};r(e,0,n)}function u(e,t){return e.every(function(e,n){return e===t[n]})}function c(e){var t={};e.forEach(function(e){var n=e.split("-").length;t[n]||(t[n]=[]),t[n].push(e)});for(var n=Object.keys(t).sort(),r=function(e){n[e+1]&&t[n[e]].forEach(function(r){for(var o=function(e){t[n[e]].forEach(function(o,i){u(r.split("-"),o.split("-"))&&(t[n[e]][i]=null)}),t[n[e]]=t[n[e]].filter(function(e){return e})},i=e+1;i<n.length;i++)o(i)})},o=0;o<n.length;o++)r(o);var i=[];return n.forEach(function(e){i=i.concat(t[e])}),i}function p(e){var t=e.match(/(.+)(-[^-]+)$/),n="";return t&&3===t.length&&(n=t[1]),n}function f(e){return e.split("-")}function d(e,t,n){var r=Object.keys(e);r.forEach(function(o,i){var a=f(o),s=!1;t.forEach(function(t){var l=f(t);a.length>l.length&&u(l,a)&&(e[o].halfChecked=!1,e[o].checked=n,r[i]=null),a[0]===l[0]&&a[1]===l[1]&&(s=!0)}),s||(r[i]=null)}),r=r.filter(function(e){return e});for(var o=function(n){var o=function a(o){var i=f(o).length;if(!(i<=2)){var s=0,l=0,c=p(o);r.forEach(function(r){var o=f(r);if(o.length===i&&u(f(c),o))if(s++,e[r].checked){l++;var a=t.indexOf(r);a>-1&&(t.splice(a,1),a<=n&&n--)}else e[r].halfChecked&&(l+=.5)});var d=e[c];0===l?(d.checked=!1,d.halfChecked=!1):l===s?(d.checked=!0,d.halfChecked=!1):(d.halfChecked=!0,d.checked=!1),a(c)}};o(t[n],n),i=n},i=0;i<t.length;i++)o(i)}function h(e){var t=[],n=[],r=[],o=[];return Object.keys(e).forEach(function(i){var a=e[i];a.checked?(n.push(a.key),r.push(a.node),o.push({node:a.node,pos:i})):a.halfChecked&&t.push(a.key)}),{halfCheckedKeys:t,checkedKeys:n,checkedNodes:r,checkedNodesPositions:o,treeNodesStates:e}}function y(e,t){return t?{checked:e,halfChecked:t}:e}function v(e,t){if(e===t)return!0;if(null===e||"undefined"==typeof e||null===t||"undefined"==typeof t)return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}Object.defineProperty(t,"__esModule",{value:!0}),t.browser=o,t.getOffset=i,t.loopAllChildren=l,t.isInclude=u,t.filterParentPosition=c,t.handleCheckState=d,t.getCheck=h,t.getStrictlyValue=y,t.arraysEqual=v;var m=n(1),g=r(m)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(117),i=r(o),a=n(1),s=r(a),l=s["default"].createClass({displayName:"LazyRenderBox",propTypes:{children:a.PropTypes.any,className:a.PropTypes.string,visible:a.PropTypes.bool,hiddenClassName:a.PropTypes.string},shouldComponentUpdate:function(e){return e.hiddenClassName||e.visible},render:function(){var e=this.props,t=e.hiddenClassName,n=e.visible,r=(0,i["default"])(e,["hiddenClassName","visible"]);return t||s["default"].Children.count(r.children)>1?(!n&&t&&(r.className+=" "+t),s["default"].createElement("div",r)):s["default"].Children.only(r.children)}});t["default"]=l,e.exports=t["default"]},function(e,t){"use strict";function n(){return"rc-upload-"+r+"-"+ ++o}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n;var r=+new Date,o=0;e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e}var o=n(1);e.exports=function(e){return o.Children.map(e,r)}},function(e,t){"use strict";e.exports=function(e,t){for(var n=t;n;){if(n===e)return!0;n=n.parentNode}return!1}},function(e,t){"use strict";var n={className:"",accessibility:!0,adaptiveHeight:!1,arrows:!0,autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,infinite:!0,initialSlide:0,lazyLoad:!1,pauseOnHover:!0,responsive:null,rtl:!1,slide:"div",slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,variableWidth:!1,vertical:!1,waitForAnimate:!0,afterChange:null,beforeChange:null,edgeEvent:null,init:null,swipeEvent:null,nextArrow:null,prevArrow:null};e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(1),i=r(o),a=n(4),s=r(a),l=n(174),u=n(10),c=r(u),p={initialize:function(e){var t=i["default"].Children.count(e.children),n=this.getWidth(s["default"].findDOMNode(this.list)),r=this.getWidth(s["default"].findDOMNode(this.track)),o=r/e.slidesToShow,a=e.rtl?t-1-e.initialSlide:e.initialSlide;this.setState({slideCount:t,slideWidth:o,listWidth:n,trackWidth:r,currentSlide:a},function(){var t=(0,l.getTrackLeft)((0,c["default"])({slideIndex:this.state.currentSlide,trackRef:this.track},e,this.state)),n=(0,l.getTrackCSS)((0,c["default"])({left:t},e,this.state));this.setState({trackStyle:n}),this.autoPlay()})},update:function(e){var t=i["default"].Children.count(e.children),n=this.getWidth(s["default"].findDOMNode(this.list)),r=this.getWidth(s["default"].findDOMNode(this.track)),o=this.getWidth(s["default"].findDOMNode(this))/e.slidesToShow; e.autoplay||this.pause(),this.setState({slideCount:t,slideWidth:o,listWidth:n,trackWidth:r},function(){var t=(0,l.getTrackLeft)((0,c["default"])({slideIndex:this.state.currentSlide,trackRef:this.track},e,this.state)),n=(0,l.getTrackCSS)((0,c["default"])({left:t},e,this.state));this.setState({trackStyle:n})})},getWidth:function(e){return e.getBoundingClientRect().width||e.offsetWidth},adaptHeight:function(){if(this.props.adaptiveHeight){var e='[data-index="'+this.state.currentSlide+'"]';if(this.list){var t=s["default"].findDOMNode(this.list);t.style.height=t.querySelector(e).offsetHeight+"px"}}},slideHandler:function(e){var t,n,r,o,i,a=this;if(!this.props.waitForAnimate||!this.state.animating){if(this.props.fade){if(n=this.state.currentSlide,this.props.infinite===!1&&(e<0||e>=this.state.slideCount))return;return t=e<0?e+this.state.slideCount:e>=this.state.slideCount?e-this.state.slideCount:e,this.props.lazyLoad&&this.state.lazyLoadedList.indexOf(t)<0&&this.setState({lazyLoadedList:this.state.lazyLoadedList.concat(t)}),i=function(){a.setState({animating:!1}),a.props.afterChange&&a.props.afterChange(t),delete a.animationEndCallback},this.setState({animating:!0,currentSlide:t},function(){this.animationEndCallback=setTimeout(i,this.props.speed)}),this.props.beforeChange&&this.props.beforeChange(this.state.currentSlide,t),void this.autoPlay()}if(t=e,n=t<0?this.props.infinite===!1?0:this.state.slideCount%this.props.slidesToScroll!==0?this.state.slideCount-this.state.slideCount%this.props.slidesToScroll:this.state.slideCount+t:t>=this.state.slideCount?this.props.infinite===!1?this.state.slideCount-this.props.slidesToShow:this.state.slideCount%this.props.slidesToScroll!==0?0:t-this.state.slideCount:t,r=(0,l.getTrackLeft)((0,c["default"])({slideIndex:t,trackRef:this.track},this.props,this.state)),o=(0,l.getTrackLeft)((0,c["default"])({slideIndex:n,trackRef:this.track},this.props,this.state)),this.props.infinite===!1&&(r=o),this.props.beforeChange&&this.props.beforeChange(this.state.currentSlide,n),this.props.lazyLoad){for(var s=!0,u=[],p=t;p<t+this.props.slidesToShow;p++)s=s&&this.state.lazyLoadedList.indexOf(p)>=0,s||u.push(p);s||this.setState({lazyLoadedList:this.state.lazyLoadedList.concat(u)})}if(this.props.useCSS===!1)this.setState({currentSlide:n,trackStyle:(0,l.getTrackCSS)((0,c["default"])({left:o},this.props,this.state))},function(){this.props.afterChange&&this.props.afterChange(n)});else{var f={animating:!1,currentSlide:n,trackStyle:(0,l.getTrackCSS)((0,c["default"])({left:o},this.props,this.state)),swipeLeft:null};i=function(){a.setState(f),a.props.afterChange&&a.props.afterChange(n),delete a.animationEndCallback},this.setState({animating:!0,currentSlide:n,trackStyle:(0,l.getTrackAnimateCSS)((0,c["default"])({left:r},this.props,this.state))},function(){this.animationEndCallback=setTimeout(i,this.props.speed)})}this.autoPlay()}},swipeDirection:function(e){var t,n,r,o;return t=e.startX-e.curX,n=e.startY-e.curY,r=Math.atan2(n,t),o=Math.round(180*r/Math.PI),o<0&&(o=360-Math.abs(o)),o<=45&&o>=0||o<=360&&o>=315?this.props.rtl===!1?"left":"right":o>=135&&o<=225?this.props.rtl===!1?"right":"left":"vertical"},autoPlay:function(){var e=this;if(!this.state.autoPlayTimer){var t=function(){if(e.state.mounted){var t=e.props.rtl?e.state.currentSlide-e.props.slidesToScroll:e.state.currentSlide+e.props.slidesToScroll;e.slideHandler(t)}};this.props.autoplay&&this.setState({autoPlayTimer:window.setInterval(t,this.props.autoplaySpeed)})}},pause:function(){this.state.autoPlayTimer&&(window.clearInterval(this.state.autoPlayTimer),this.setState({autoPlayTimer:null}))}};t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.getTrackLeft=t.getTrackAnimateCSS=t.getTrackCSS=void 0;var o=n(4),i=r(o),a=function(e,t){return t.reduce(function(t,n){return t&&e.hasOwnProperty(n)},!0)?null:console.error("Keys Missing",e)},s=t.getTrackCSS=function(e){a(e,["left","variableWidth","slideCount","slidesToShow","slideWidth"]);var t;t=e.variableWidth?(e.slideCount+2*e.slidesToShow)*e.slideWidth:e.centerMode?(e.slideCount+2*(e.slidesToShow+1))*e.slideWidth:(e.slideCount+2*e.slidesToShow)*e.slideWidth;var n={opacity:1,width:t,WebkitTransform:"translate3d("+e.left+"px, 0px, 0px)",transform:"translate3d("+e.left+"px, 0px, 0px)",transition:"",WebkitTransition:"",msTransform:"translateX("+e.left+"px)"};return!window.addEventListener&&window.attachEvent&&(n.marginLeft=e.left+"px"),n};t.getTrackAnimateCSS=function(e){a(e,["left","variableWidth","slideCount","slidesToShow","slideWidth","speed","cssEase"]);var t=s(e);return t.WebkitTransition="-webkit-transform "+e.speed+"ms "+e.cssEase,t.transition="transform "+e.speed+"ms "+e.cssEase,t},t.getTrackLeft=function(e){a(e,["slideIndex","trackRef","infinite","centerMode","slideCount","slidesToShow","slidesToScroll","slideWidth","listWidth","variableWidth"]);var t,n,r=0;if(e.fade)return 0;if(e.infinite)e.slideCount>e.slidesToShow&&(r=e.slideWidth*e.slidesToShow*-1),e.slideCount%e.slidesToScroll!==0&&e.slideIndex+e.slidesToScroll>e.slideCount&&e.slideCount>e.slidesToShow&&(r=e.slideIndex>e.slideCount?(e.slidesToShow-(e.slideIndex-e.slideCount))*e.slideWidth*-1:e.slideCount%e.slidesToScroll*e.slideWidth*-1);else if(e.slideCount%e.slidesToScroll!==0&&e.slideIndex+e.slidesToScroll>e.slideCount&&e.slideCount>e.slidesToShow){var o=e.slidesToShow-e.slideCount%e.slidesToScroll;r=o*e.slideWidth}if(e.centerMode&&(e.infinite?r+=e.slideWidth*Math.floor(e.slidesToShow/2):r=e.slideWidth*Math.floor(e.slidesToShow/2)),t=e.slideIndex*e.slideWidth*-1+r,e.variableWidth===!0){var s;e.slideCount<=e.slidesToShow||e.infinite===!1?n=i["default"].findDOMNode(e.trackRef).childNodes[e.slideIndex]:(s=e.slideIndex+e.slidesToShow,n=i["default"].findDOMNode(e.trackRef).childNodes[s]),t=n?n.offsetLeft*-1:0,e.centerMode===!0&&(n=e.infinite===!1?i["default"].findDOMNode(e.trackRef).children[e.slideIndex]:i["default"].findDOMNode(e.trackRef).children[e.slideIndex+e.slidesToShow+1],t=n?n.offsetLeft*-1:0,t+=(e.listWidth-n.offsetWidth)/2)}return t}},function(e,t,n){function r(e){return n(o(e))}function o(e){return i[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var i={"./affix/index.jsx":200,"./affix/style/index.js":201,"./alert/index.jsx":202,"./alert/style/index.js":203,"./back-top/index.jsx":204,"./back-top/style/index.js":205,"./badge/index.jsx":207,"./badge/style/index.js":208,"./breadcrumb/index.jsx":210,"./breadcrumb/style/index.js":211,"./button/index.jsx":29,"./button/style/index.js":42,"./calendar/index.jsx":215,"./calendar/style/index.js":217,"./card/index.jsx":218,"./card/style/index.js":219,"./carousel/index.jsx":220,"./carousel/style/index.js":221,"./cascader/index.jsx":222,"./cascader/style/index.js":223,"./checkbox/index.jsx":34,"./checkbox/style/index.js":35,"./col/index.js":92,"./col/style/index.js":225,"./collapse/index.jsx":226,"./collapse/style/index.js":227,"./date-picker/index.jsx":231,"./date-picker/style/index.js":232,"./dropdown/index.jsx":95,"./dropdown/style/index.js":96,"./form/index.jsx":238,"./form/style/index.js":239,"./icon/index.jsx":6,"./icon/style/index.js":240,"./input-number/index.jsx":241,"./input-number/style/index.js":242,"./input/index.jsx":98,"./input/style/index.js":23,"./layout/index.jsx":58,"./layout/style/index.js":99,"./locale-provider/index.jsx":248,"./locale-provider/style/index.js":249,"./menu/index.jsx":250,"./menu/style/index.js":251,"./message/index.jsx":252,"./message/style/index.js":253,"./modal/index.jsx":255,"./modal/style/index.js":256,"./notification/index.jsx":257,"./notification/style/index.js":258,"./pagination/index.jsx":102,"./pagination/style/index.js":103,"./popconfirm/index.jsx":262,"./popconfirm/style/index.js":263,"./popover/index.jsx":264,"./popover/style/index.js":104,"./progress/index.jsx":105,"./progress/style/index.js":106,"./queue-anim/index.jsx":266,"./queue-anim/style/index.js":267,"./radio/index.jsx":43,"./radio/style/index.js":61,"./rate/index.jsx":269,"./rate/style/index.js":270,"./row/index.js":108,"./row/style/index.js":271,"./select/index.jsx":44,"./select/style/index.js":45,"./slider/index.jsx":272,"./slider/style/index.js":273,"./spin/index.jsx":109,"./spin/style/index.js":110,"./steps/index.jsx":274,"./steps/style/index.js":275,"./style/index.js":276,"./switch/index.jsx":277,"./switch/style/index.js":278,"./table/index.jsx":281,"./table/style/index.js":282,"./tabs/index.jsx":284,"./tabs/style/index.js":285,"./tag/index.jsx":286,"./tag/style/index.js":287,"./time-picker/index.jsx":288,"./time-picker/style/index.js":112,"./timeline/index.jsx":290,"./timeline/style/index.js":291,"./tooltip/index.jsx":62,"./tooltip/style/index.js":114,"./transfer/index.jsx":292,"./transfer/style/index.js":295,"./tree-select/index.jsx":296,"./tree-select/style/index.js":297,"./tree/index.jsx":298,"./tree/style/index.js":299,"./upload/index.jsx":301,"./upload/style/index.js":302,"./validation/index.jsx":304,"./validation/style/index.js":305};r.keys=function(){return Object.keys(i)},r.resolve=o,e.exports=r,r.id=175},function(e,t){"use strict";function n(){return!1}function r(){return!0}function o(){this.timeStamp=Date.now(),this.target=void 0,this.currentTarget=void 0}Object.defineProperty(t,"__esModule",{value:!0}),o.prototype={isEventObject:1,constructor:o,isDefaultPrevented:n,isPropagationStopped:n,isImmediatePropagationStopped:n,preventDefault:function(){this.isDefaultPrevented=r},stopPropagation:function(){this.isPropagationStopped=r},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=r,this.stopPropagation()},halt:function(e){e?this.stopImmediatePropagation():this.stopPropagation(),this.preventDefault()}},t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return null===e||void 0===e}function i(){return f}function a(){return d}function s(e){var t=e.type,n="function"==typeof e.stopPropagation||"boolean"==typeof e.cancelBubble;u["default"].call(this),this.nativeEvent=e;var r=a;"defaultPrevented"in e?r=e.defaultPrevented?i:a:"getPreventDefault"in e?r=e.getPreventDefault()?i:a:"returnValue"in e&&(r=e.returnValue===d?i:a),this.isDefaultPrevented=r;var o=[],s=void 0,l=void 0,c=void 0,p=h.concat();for(y.forEach(function(e){t.match(e.reg)&&(p=p.concat(e.props),e.fix&&o.push(e.fix))}),l=p.length;l;)c=p[--l],this[c]=e[c];for(!this.target&&n&&(this.target=e.srcElement||document),this.target&&3===this.target.nodeType&&(this.target=this.target.parentNode),l=o.length;l;)(s=o[--l])(this,e);this.timeStamp=e.timeStamp||Date.now()}Object.defineProperty(t,"__esModule",{value:!0});var l=n(176),u=r(l),c=n(10),p=r(c),f=!0,d=!1,h=["altKey","bubbles","cancelable","ctrlKey","currentTarget","eventPhase","metaKey","shiftKey","target","timeStamp","view","type"],y=[{reg:/^key/,props:["char","charCode","key","keyCode","which"],fix:function(e,t){o(e.which)&&(e.which=o(t.charCode)?t.keyCode:t.charCode),void 0===e.metaKey&&(e.metaKey=e.ctrlKey)}},{reg:/^touch/,props:["touches","changedTouches","targetTouches"]},{reg:/^hashchange$/,props:["newURL","oldURL"]},{reg:/^gesturechange$/i,props:["rotation","scale"]},{reg:/^(mousewheel|DOMMouseScroll)$/,props:[],fix:function(e,t){var n=void 0,r=void 0,o=void 0,i=t.wheelDelta,a=t.axis,s=t.wheelDeltaY,l=t.wheelDeltaX,u=t.detail;i&&(o=i/120),u&&(o=0-(u%3===0?u/3:u)),void 0!==a&&(a===e.HORIZONTAL_AXIS?(r=0,n=0-o):a===e.VERTICAL_AXIS&&(n=0,r=o)),void 0!==s&&(r=s/120),void 0!==l&&(n=-1*l/120),n||r||(r=o),void 0!==n&&(e.deltaX=n),void 0!==r&&(e.deltaY=r),void 0!==o&&(e.delta=o)}},{reg:/^mouse|contextmenu|click|mspointer|(^DOMMouseScroll$)/i,props:["buttons","clientX","clientY","button","offsetX","relatedTarget","which","fromElement","toElement","offsetY","pageX","pageY","screenX","screenY"],fix:function(e,t){var n=void 0,r=void 0,i=void 0,a=e.target,s=t.button;return a&&o(e.pageX)&&!o(t.clientX)&&(n=a.ownerDocument||document,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||void 0===s||(1&s?e.which=1:2&s?e.which=3:4&s?e.which=2:e.which=0),!e.relatedTarget&&e.fromElement&&(e.relatedTarget=e.fromElement===a?e.toElement:e.fromElement),e}}],v=u["default"].prototype;(0,p["default"])(s.prototype,v,{constructor:s,preventDefault:function(){var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=d,v.preventDefault.call(this)},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=f,v.stopPropagation.call(this)}}),t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){function r(t){var r=new a["default"](t);n.call(e,r)}return e.addEventListener?(e.addEventListener(t,r,!1),{remove:function(){e.removeEventListener(t,r,!1)}}):e.attachEvent?(e.attachEvent("on"+t,r),{remove:function(){e.detachEvent("on"+t,r)}}):void 0}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var i=n(177),a=r(i);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){this.rules=null,this._messages=c.messages,this.define(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},s=n(5),l=n(191),u=r(l),c=n(180),p=n(8);o.prototype={messages:function(e){return e&&(this._messages=(0,s.deepMerge)((0,c.newMessages)(),e)),this._messages},define:function(e){if(!e)throw new Error("Cannot configure a schema with no rules");if("object"!==("undefined"==typeof e?"undefined":a(e))||Array.isArray(e))throw new Error("Rules must be an object");this.rules={};var t=void 0,n=void 0;for(t in e)e.hasOwnProperty(t)&&(n=e[t],this.rules[t]=Array.isArray(n)?n:[n])},validate:function(e){function t(e){function t(e){Array.isArray(e)?o=o.concat.apply(o,e):o.push(e)}var n=void 0,r=void 0,o=[],i={};for(n=0;n<e.length;n++)t(e[n]);if(o.length)for(n=0;n<o.length;n++)r=o[n].field,i[r]=i[r]||[],i[r].push(o[n]);else o=null,i=null;d(o,i)}var n=this,r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],l=arguments[2],u=e,f=r,d=l;if("function"==typeof f&&(d=f,f={}),!this.rules||0===Object.keys(this.rules).length)return void(d&&d());if(f.messages){var h=this.messages();h===c.messages&&(h=(0,c.newMessages)()),(0,s.deepMerge)(h,f.messages),f.messages=h}else f.messages=this.messages();f.error=p.error;var y=void 0,v=void 0,m={},g=f.keys||Object.keys(this.rules);g.forEach(function(t){y=n.rules[t],v=u[t],y.forEach(function(r){var o=r;"function"==typeof o.transform&&(u===e&&(u=i({},u)),v=u[t]=o.transform(v)),o="function"==typeof o?{validator:o}:i({},o),o.validator=n.getValidationMethod(o),o.field=t,o.fullField=o.fullField||t,o.type=n.getType(o),o.validator&&(m[t]=m[t]||[],m[t].push({rule:o,value:v,source:u,field:t}))})});var b={};(0,s.asyncMap)(m,f,function(e,t){function n(e,t){return i({},t,{fullField:l.fullField+"."+e})}function r(){var r=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],a=r;if(Array.isArray(a)||(a=[a]),a.length&&(0,s.warning)("async-validator:",a),a.length&&l.message&&(a=[].concat(l.message)),a=a.map((0,s.complementError)(l)),(f.first||f.fieldFirst)&&a.length)return b[l.field]=1,t(a);if(u){if(l.required&&!e.value)return a=l.message?[].concat(l.message).map((0,s.complementError)(l)):[f.error(l,(0,s.format)(f.messages.required,l.field))],t(a);var c={};if(l.defaultField)for(var p in e.value)e.value.hasOwnProperty(p)&&(c[p]=l.defaultField);c=i({},c,e.rule.fields);for(var d in c)if(c.hasOwnProperty(d)){var h=Array.isArray(c[d])?c[d]:[c[d]];c[d]=h.map(n.bind(null,d))}var y=new o(c);y.messages(f.messages),e.rule.options&&(e.rule.options.messages=f.messages,e.rule.options.error=f.error),y.validate(e.value,e.rule.options||f,function(e){t(e&&e.length?a.concat(e):e)})}else t(a)}var l=e.rule,u=!("object"!==l.type&&"array"!==l.type||"object"!==a(l.fields)&&"object"!==a(l.defaultField));u=u&&(l.required||!l.required&&e.value),l.field=e.field,l.validator(l,e.value,r,e.source,f)},function(e){t(e)})},getType:function(e){if(void 0===e.type&&e.pattern instanceof RegExp&&(e.type="pattern"),"function"!=typeof e.validator&&e.type&&!u["default"].hasOwnProperty(e.type))throw new Error((0,s.format)("Unknown rule type %s",e.type));return e.type||"string"},getValidationMethod:function(e){if("function"==typeof e.validator)return e.validator;var t=Object.keys(e);return 1===t.length&&"required"===t[0]?u["default"].required:u["default"][this.getType(e)]||!1}},o.register=function(e,t){if("function"!=typeof t)throw new Error("Cannot register a validator by type, validator is not a function");u["default"][e]=t},o.messages=c.messages,t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(){return{"default":"Validation error on field %s",required:"%s is required","enum":"%s must be one of %s",whitespace:"%s cannot be empty",date:{format:"%s date %s is invalid for format %s",parse:"%s date could not be parsed, %s is invalid ",invalid:"%s date %s is invalid"},types:{string:"%s is not a %s",method:"%s is not a %s (function)",array:"%s is not an %s",object:"%s is not an %s",number:"%s is not a %s",date:"%s is not a %s","boolean":"%s is not a %s",integer:"%s is not an %s","float":"%s is not a %s",regexp:"%s is not a valid %s",email:"%s is not a valid %s",url:"%s is not a valid %s",hex:"%s is not a valid %s"},string:{len:"%s must be exactly %s characters",min:"%s must be at least %s characters",max:"%s cannot be longer than %s characters",range:"%s must be between %s and %s characters"},number:{len:"%s must equal %s",min:"%s cannot be less than %s",max:"%s cannot be greater than %s",range:"%s must be between %s and %s"},array:{len:"%s must be exactly %s in length",min:"%s cannot be less than %s in length",max:"%s cannot be greater than %s in length",range:"%s must be between %s and %s in length"},pattern:{mismatch:"%s value %s does not match pattern %s"},clone:function(){var e=JSON.parse(JSON.stringify(this));return e.clone=this.clone,e}}}Object.defineProperty(t,"__esModule",{value:!0}),t.newMessages=n;t.messages=n()},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o){e[s]=Array.isArray(e[s])?e[s]:[],e[s].indexOf(t)===-1&&r.push(a.format(o.messages[s],e.fullField,e[s].join(", ")))}Object.defineProperty(t,"__esModule",{value:!0});var i=n(5),a=r(i),s="enum";t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o){e.pattern instanceof RegExp&&(e.pattern.test(t)||r.push(a.format(o.messages.pattern.mismatch,e.fullField,t,e.pattern)))}Object.defineProperty(t,"__esModule",{value:!0});var i=n(5),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o){var i="number"==typeof e.len,s="number"==typeof e.min,l="number"==typeof e.max,u=t,c=null,p="number"==typeof t,f="string"==typeof t,d=Array.isArray(t);return p?c="number":f?c="string":d&&(c="array"),!!c&&((f||d)&&(u=t.length),void(i?u!==e.len&&r.push(a.format(o.messages[c].len,e.fullField,e.len)):s&&!l&&u<e.min?r.push(a.format(o.messages[c].min,e.fullField,e.min)):l&&!s&&u>e.max?r.push(a.format(o.messages[c].max,e.fullField,e.max)):s&&l&&(u<e.min||u>e.max)&&r.push(a.format(o.messages[c].range,e.fullField,e.min,e.max))))}Object.defineProperty(t,"__esModule",{value:!0});var i=n(5),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function i(e,t,n,r,o){if(e.required&&void 0===t)return void(0,c["default"])(e,t,n,r,o);var i=["integer","float","array","regexp","object","method","email","number","date","url","hex"],s=e.type;i.indexOf(s)>-1?f[s](t)||r.push(l.format(o.messages.types[s],e.fullField,e.type)):s&&("undefined"==typeof t?"undefined":a(t))!==e.type&&r.push(l.format(o.messages.types[s],e.fullField,e.type))}Object.defineProperty(t,"__esModule",{value:!0});var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},s=n(5),l=o(s),u=n(87),c=r(u),p={email:/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/,url:new RegExp("^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$","i"),hex:/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i},f={integer:function(e){return f.number(e)&&parseInt(e,10)===e},"float":function(e){return f.number(e)&&!f.integer(e)},array:function(e){return Array.isArray(e)},regexp:function(e){if(e instanceof RegExp)return!0;try{return!!new RegExp(e)}catch(t){return!1}},date:function(e){return"function"==typeof e.getTime&&"function"==typeof e.getMonth&&"function"==typeof e.getYear},number:function(e){return!isNaN(e)&&"number"==typeof e},object:function(e){return"object"===("undefined"==typeof e?"undefined":a(e))&&!f.array(e)},method:function(e){return"function"==typeof e},email:function(e){return"string"==typeof e&&!!e.match(p.email)},url:function(e){return"string"==typeof e&&!!e.match(p.url)},hex:function(e){return"string"==typeof e&&!!e.match(p.hex)}};t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o){(/^\s+$/.test(t)||""===t)&&r.push(a.format(o.messages.whitespace,e.fullField))}Object.defineProperty(t,"__esModule",{value:!0});var i=n(5),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t,"array")&&!e.required)return n();a["default"].required(e,t,r,i,o,"array"),(0,s.isEmptyValue)(t,"array")||(a["default"].type(e,t,r,i,o),a["default"].range(e,t,r,i,o))}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,i.isEmptyValue)(t)&&!e.required)return n();s["default"].required(e,t,r,a,o),void 0!==t&&s["default"].type(e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(5),a=n(8),s=r(a);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();a["default"].required(e,t,r,i,o),(0,s.isEmptyValue)(t)||(a["default"].type(e,t,r,i,o),t&&a["default"].range(e,t.getTime(),r,i,o))}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],u=e.required||!e.required&&r.hasOwnProperty(e.field);if(u){if((0,s.isEmptyValue)(t)&&!e.required)return n();a["default"].required(e,t,r,i,o),t&&a["default"][l](e,t,r,i,o)}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5),l="enum";t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();a["default"].required(e,t,r,i,o),void 0!==t&&(a["default"].type(e,t,r,i,o),a["default"].range(e,t,r,i,o))}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";e.exports={string:n(199),method:n(193),number:n(194),"boolean":n(187),regexp:n(197),integer:n(192),"float":n(190),array:n(186),object:n(195),"enum":n(189),pattern:n(196),email:n(57),url:n(57),date:n(188),hex:n(57),required:n(198)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();a["default"].required(e,t,r,i,o),void 0!==t&&(a["default"].type(e,t,r,i,o),a["default"].range(e,t,r,i,o))}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();a["default"].required(e,t,r,i,o),void 0!==t&&a["default"].type(e,t,r,i,o)}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();a["default"].required(e,t,r,i,o),void 0!==t&&(a["default"].type(e,t,r,i,o),a["default"].range(e,t,r,i,o))}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();a["default"].required(e,t,r,i,o),void 0!==t&&a["default"].type(e,t,r,i,o)}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t,"string")&&!e.required)return n();a["default"].required(e,t,r,i,o),(0,s.isEmptyValue)(t,"string")||a["default"].pattern(e,t,r,i,o)}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();a["default"].required(e,t,r,i,o),(0,s.isEmptyValue)(t)||a["default"].type(e,t,r,i,o)}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=Array.isArray(t)?"array":"undefined"==typeof t?"undefined":i(t);s["default"].required(e,t,r,a,o,l),n(a)}Object.defineProperty(t,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},a=n(8),s=r(a);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t,"string")&&!e.required)return n();a["default"].required(e,t,r,i,o,"string"),(0,s.isEmptyValue)(t,"string")||(a["default"].type(e,t,r,i,o),a["default"].range(e,t,r,i,o),a["default"].pattern(e,t,r,i,o),e.whitespace===!0&&a["default"].whitespace(e,t,r,i,o))}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(e,t){var n=t?"pageYOffset":"pageXOffset",r=t?"scrollTop":"scrollLeft",o=e===window,i=o?e[n]:e[r];return o&&"number"!=typeof i&&(i=window.document.documentElement[r]),i}function u(e){return e!==window?e.getBoundingClientRect():{top:0,left:0,bottom:0}}function c(e,t){var n=e.getBoundingClientRect(),r=u(t),o=l(t,!0),i=l(t,!1),a=window.document.body,s=a.clientTop||0,c=a.clientLeft||0;return{top:n.top-r.top+o-s,left:n.left-r.left+i-c}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var p,f,d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h=n(1),y=r(h),v=n(4),m=r(v),g=n(20),b=r(g),P=n(2),C=r(P),T=n(22),O=r(T),w=n(41),x=r(w),E=(f=p=function(e){function t(n){i(this,t);var r=a(this,e.call(this,n));return r.updatePosition=function(e){var t=r.props,n=t.offsetTop,o=t.offsetBottom,i=t.offset,a=t.target,s=a();n=n||i;var p=l(s,!0),f=c(m["default"].findDOMNode(r),s),d={width:r.refs.fixedNode.offsetWidth,height:r.refs.fixedNode.offsetHeight},h={};"number"!=typeof n&&"number"!=typeof o?(h.top=!0,n=0):(h.top="number"==typeof n,h.bottom="number"==typeof o);var y=u(s),v=s.innerHeight||s.clientHeight;if(p>f.top-n&&h.top)r.setAffixStyle(e,{position:"fixed",top:y.top+n,left:y.left+f.left,width:m["default"].findDOMNode(r).offsetWidth}),r.setPlaceholderStyle(e,{width:m["default"].findDOMNode(r).offsetWidth,height:m["default"].findDOMNode(r).offsetHeight});else if(p<f.top+d.height+o-v&&h.bottom){var g=s===window?0:window.innerHeight-y.bottom;r.setAffixStyle(e,{position:"fixed",bottom:g+o,left:y.left+f.left,width:m["default"].findDOMNode(r).offsetWidth}),r.setPlaceholderStyle(e,{width:m["default"].findDOMNode(r).offsetWidth,height:m["default"].findDOMNode(r).offsetHeight})}else r.setAffixStyle(e,null),r.setPlaceholderStyle(e,null)},r.state={affixStyle:null,placeholderStyle:null},r}return s(t,e),t.prototype.setAffixStyle=function(e,t){var n=this,r=this.props,o=r.onChange,i=r.target,a=this.state.affixStyle,s=i()===window;"scroll"===e.type&&a&&t&&s||(0,x["default"])(t,a)||this.setState({affixStyle:t},function(){var e=!!n.state.affixStyle; (t&&!a||!t&&a)&&o(e)})},t.prototype.setPlaceholderStyle=function(e,t){var n=this.state.placeholderStyle;"resize"!==e.type&&((0,x["default"])(t,n)||this.setState({placeholderStyle:t}))},t.prototype.componentDidMount=function(){(0,O["default"])(!("offset"in this.props),"`offset` prop of Affix is deprecated, use `offsetTop` instead.");var e=this.props.target;this.setTargetEventListeners(e)},t.prototype.componentWillReceiveProps=function(e){this.props.target!==e.target&&(this.clearScrollEventListeners(),this.setTargetEventListeners(e.target),this.updatePosition({}))},t.prototype.componentWillUnmount=function(){this.clearScrollEventListeners()},t.prototype.setTargetEventListeners=function(e){var t=e();this.scrollEvent=(0,b["default"])(t,"scroll",this.updatePosition),this.resizeEvent=(0,b["default"])(t,"resize",this.updatePosition)},t.prototype.clearScrollEventListeners=function(){var e=this;["scrollEvent","resizeEvent"].forEach(function(t){e[t]&&e[t].remove()})},t.prototype.render=function(){var e=(0,C["default"])({"ant-affix":this.state.affixStyle}),t=d({},this.props);return delete t.offsetTop,delete t.offsetBottom,delete t.target,y["default"].createElement("div",d({},t,{style:this.state.placeholderStyle}),y["default"].createElement("div",{className:e,ref:"fixedNode",style:this.state.affixStyle},this.props.children))},t}(y["default"].Component),p.propTypes={offsetTop:y["default"].PropTypes.number,offsetBottom:y["default"].PropTypes.number,target:y["default"].PropTypes.func},p.defaultProps={target:function(){return window},onChange:function(){}},f);t["default"]=E,e.exports=t["default"]},[557,516],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(4),h=r(d),y=n(9),v=r(y),m=n(6),g=r(m),b=n(2),P=r(b),C=(c=u=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return r.handleClose=function(e){e.preventDefault();var t=h["default"].findDOMNode(r);t.style.height=t.offsetHeight+"px",t.style.height=t.offsetHeight+"px",r.setState({closing:!1}),r.props.onClose(e)},r.animationEnd=function(){r.setState({closed:!0,closing:!0})},r.state={closing:!0,closed:!1},r}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.closable,r=t.description,o=t.type,a=t.prefixCls,s=t.message,l=t.closeText,u=t.showIcon,c="";switch(o){case"success":c="check-circle";break;case"info":c="info-circle";break;case"error":c="cross-circle";break;case"warning":c="exclamation-circle";break;default:c="default"}r&&(c+="-o");var p=(0,P["default"])((e={},i(e,a,!0),i(e,a+"-"+o,!0),i(e,a+"-close",!this.state.closing),i(e,a+"-with-description",!!r),i(e,a+"-no-icon",!u),e));return l&&(n=!0),this.state.closed?null:f["default"].createElement(v["default"],{component:"",showProp:"data-show",transitionName:a+"-slide-up",onEnd:this.animationEnd},f["default"].createElement("div",{"data-show":this.state.closing,className:p},u?f["default"].createElement(g["default"],{className:"ant-alert-icon",type:c}):null,f["default"].createElement("span",{className:a+"-message"},s),f["default"].createElement("span",{className:a+"-description"},r),n?f["default"].createElement("a",{onClick:this.handleClose,className:a+"-close-icon"},l||f["default"].createElement(g["default"],{type:"cross"})):null))},t}(f["default"].Component),u.defaultProps={prefixCls:"ant-alert",showIcon:!1,onClose:function(){},type:"info"},c);t["default"]=C,e.exports=t["default"]},[557,517],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function c(e,t){if("undefined"==typeof window)return 0;var n=t?"pageYOffset":"pageXOffset",r=t?"scrollTop":"scrollLeft",o=e===window,i=o?e[n]:e[r];return o&&"number"!=typeof i&&(i=window.document.documentElement[r]),i}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var p,f,d,h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},y=n(1),v=r(y),m=n(9),g=r(m),b=n(6),P=r(b),C=n(20),T=r(C),O=n(2),w=r(O),x=n(27),E=r(x),S=(f=p=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));d.call(r);var o=c(n.target(),!0);return r.state={visible:o>n.visibilityHeight},r}return u(t,e),t.prototype.setScrollTop=function(e){var t=this.props.target();t===window?(document.body.scrollTop=e,document.documentElement.scrollTop=e):t.scrollTop=e},t.prototype.componentDidMount=function(){this.scrollEvent=(0,T["default"])(this.props.target(),"scroll",this.handleScroll)},t.prototype.componentWillUnmount=function(){this.scrollEvent&&this.scrollEvent.remove()},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.children,s=a(t,["prefixCls","className","children"]),l=(0,w["default"])((e={},i(e,n,!0),i(e,r,!!r),e)),u=v["default"].createElement("div",{className:n+"-content"},v["default"].createElement(P["default"],{className:n+"-icon",type:"to-top"})),c=(0,E["default"])(s,["visibilityHeight"]);return v["default"].createElement(g["default"],{component:"",transitionName:"fade"},this.state.visible?v["default"].createElement("div",h({},c,{className:l,onClick:this.scrollToTop}),o||u):null)},t}(v["default"].Component),p.propTypes={visibilityHeight:v["default"].PropTypes.number,target:v["default"].PropTypes.func},p.defaultProps={onClick:function(){},visibilityHeight:400,target:function(){return window},prefixCls:"ant-back-top"},d=function(){var e=this;this.scrollToTop=function(t){t&&t.preventDefault(),e.setScrollTop(0),e.props.onClick(t)},this.handleScroll=function(){var t=e.props,n=t.visibilityHeight,r=t.target,o=c(r(),!0);e.setState({visible:o>n})}},f);t["default"]=S,e.exports=t["default"]},[557,518],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}function u(e){return e?e.toString().split("").reverse().map(function(e){return Number(e)}):[]}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(4),v=n(88),m=r(v),g=n(27),b=r(g),P=(p=c=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return r.state={animateStarted:!0,count:n.count},r}return l(t,e),t.prototype.componentDidMount=function(){(0,m["default"])()||((0,y.findDOMNode)(this).className+=" not-support-css-animation")},t.prototype.getPositionByNum=function(e,t){if(this.state.animateStarted)return 10+e;var n=u(this.state.count)[t],r=u(this.lastCount)[t];return this.state.count>this.lastCount?n>=r?10+e:20+e:n<=r?10+e:e},t.prototype.componentWillReceiveProps=function(e){var t=this;if("count"in e){if(this.state.count===e.count)return;this.lastCount=this.state.count,this.setState({animateStarted:!0},function(){setTimeout(function(){t.setState({animateStarted:!1,count:e.count},function(){t.props.onAnimated()})},5)})}},t.prototype.renderNumberList=function(e){for(var t=[],n=0;n<30;n++){var r=e===n?"current":null;t.push(h["default"].createElement("p",{key:n,className:r},n%10))}return t},t.prototype.renderCurrentNumber=function(e,t){var n=this.getPositionByNum(e,t),r=this.props.height,o=this.state.animateStarted||void 0===u(this.lastCount)[t];return(0,d.createElement)("span",{className:this.props.prefixCls+"-only",style:{transition:o&&"none",WebkitTransform:"translateY("+-n*r+"px)",transform:"translateY("+-n*r+"px)",height:r},key:t},this.renderNumberList(n))},t.prototype.renderNumberElement=function(){var e=this,t=this.state;return!t.count||isNaN(t.count)?t.count:u(t.count).map(function(t,n){return e.renderCurrentNumber(t,n)}).reverse()},t.prototype.render=function(){var e=this.props,t=e.component,n=e.prefixCls,r=e.className,o=i(e,["component","prefixCls","className"]),a=(0,b["default"])(o,["count","onAnimated"]),s=f({},a,{className:n+" "+r});return(0,d.createElement)(t,s,this.renderNumberElement())},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-scroll-number",count:null,component:"sup",onAnimated:function(){},height:18},c.propTypes={count:h["default"].PropTypes.oneOfType([h["default"].PropTypes.string,h["default"].PropTypes.number]),component:h["default"].PropTypes.string,onAnimated:h["default"].PropTypes.func,height:h["default"].PropTypes.number},p);t["default"]=P,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(9),v=r(y),m=n(206),g=r(m),b=n(2),P=r(b),C=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.count,r=t.prefixCls,o=t.overflowCount,s=t.className,l=t.style,u=t.children,c=t.dot,p=a(t,["count","prefixCls","overflowCount","className","style","children","dot"]);n=n>o?o+"+":n,c&&(n="");var d=!(n&&"0"!==n||c),y=r+(c?"-dot":"-count"),m=(0,P["default"])((e={},i(e,s,!!s),i(e,r,!0),i(e,r+"-not-a-wrapper",!u),e));return h["default"].createElement("span",f({className:m,title:n,style:null},p),u,h["default"].createElement(v["default"],{component:"",showProp:"data-show",transitionName:r+"-zoom",transitionAppear:!0},d?null:h["default"].createElement(g["default"],{"data-show":!d,className:y,count:n,style:l})))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-badge",count:null,dot:!1,overflowCount:99},c.propTypes={count:h["default"].PropTypes.oneOfType([h["default"].PropTypes.string,h["default"].PropTypes.number]),dot:h["default"].PropTypes.bool,overflowCount:h["default"].PropTypes.number},p);t["default"]=C,e.exports=t["default"]},[557,519],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(90),d=r(f),h=function(e,t,n){if(!e)return null;var r=Object.keys(n).join("|"),o=e.replace(new RegExp(":("+r+")","g"),function(e,t){return n[t]||e});return p["default"].createElement("span",null,o)},y=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=void 0,t=this.props,n=t.separator,r=t.prefixCls,o=t.routes,i=t.params,a=t.children,s=t.linkRender,l=t.nameRender;return o&&o.length>0?!function(){var t=[],r=o.length-1;e=o.map(function(e,o){e.path=e.path||"";var a=e.path.replace(/^\//,"");Object.keys(i).forEach(function(e){a=a.replace(":"+e,i[e])}),a&&t.push(a);var u=l(e.breadcrumbName,e,i);if(u){var c=o===r?u:s("/"+t.join("/"),u,t);return p["default"].createElement(d["default"],{separator:n,key:e.breadcrumbName||o},c)}return null})}():e=p["default"].Children.map(a,function(e,t){return(0,c.cloneElement)(e,{separator:n,key:t})}),p["default"].createElement("div",{className:r},e)},t}(p["default"].Component),l.defaultProps={prefixCls:"ant-breadcrumb",separator:"/",linkRender:function(e,t){return p["default"].createElement("a",{href:"#"+e},t)},nameRender:h},l.propTypes={prefixCls:p["default"].PropTypes.string,separator:p["default"].PropTypes.oneOfType([p["default"].PropTypes.string,p["default"].PropTypes.element]),routes:p["default"].PropTypes.array,params:p["default"].PropTypes.object,linkRender:p["default"].PropTypes.func,nameRender:p["default"].PropTypes.func},u);t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(209),i=r(o),a=n(90),s=r(a);i["default"].Item=s["default"],t["default"]=i["default"],e.exports=t["default"]},[557,520],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e){var t,n=e.size,r=e.className,a=i(e,["size","className"]),l={large:"lg",small:"sm"}[n]||"",c=(0,p["default"])((t={"ant-btn-group":!0},o(t,f+l,l),o(t,r,r),t));return u["default"].createElement("div",s({},a,{className:c}))}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=a;var l=n(1),u=r(l),c=n(2),p=r(c),f="ant-btn-group-";a.propTypes={size:u["default"].PropTypes.oneOf(["large","default","small"])},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function c(e){return"string"==typeof e}function p(e){return c(e.type)&&w(e.props.children)?m["default"].cloneElement(e,{},e.props.children.split("").join(" ")):c(e)?(w(e)&&(e=e.split("").join(" ")),m["default"].createElement("span",null,e)):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var f,d,h,y=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},v=n(1),m=r(v),g=n(2),b=r(g),P=n(4),C=n(6),T=r(C),O=/^[\u4e00-\u9fa5]{2}$/,w=O.test.bind(O),x=(d=f=function(e){function t(){var n,r,o;s(this,t);for(var i=arguments.length,a=Array(i),u=0;u<i;u++)a[u]=arguments[u];return n=r=l(this,e.call.apply(e,[this].concat(a))),h.call(r),o=n,l(r,o)}return u(t,e),t.prototype.componentWillUnmount=function(){this.clickedTimeout&&clearTimeout(this.clickedTimeout),this.timeout&&clearTimeout(this.timeout)},t.prototype.render=function(){var e,t=this.props,n=t.type,r=t.shape,o=t.size,s=t.className,l=t.htmlType,u=t.children,c=t.icon,f=t.loading,d=t.prefixCls,h=a(t,["type","shape","size","className","htmlType","children","icon","loading","prefixCls"]),v={large:"lg",small:"sm"}[o]||"",g=(0,b["default"])((e={},i(e,d,!0),i(e,d+"-"+n,n),i(e,d+"-"+r,r),i(e,d+"-"+v,v),i(e,d+"-icon-only",!u&&c),i(e,d+"-loading",f),i(e,s,s),e)),P=f?"loading":c,C=m["default"].Children.map(u,p);return m["default"].createElement("button",y({},h,{type:l||"button",className:g,onMouseUp:this.handleMouseUp,onClick:this.handleClick}),P?m["default"].createElement(T["default"],{type:P}):null,C)},t}(m["default"].Component),f.defaultProps={prefixCls:"ant-btn",onClick:function(){},loading:!1},f.propTypes={type:m["default"].PropTypes.string,shape:m["default"].PropTypes.oneOf(["circle","circle-outline"]),size:m["default"].PropTypes.oneOf(["large","default","small"]),htmlType:m["default"].PropTypes.oneOf(["submit","button","reset"]),onClick:m["default"].PropTypes.func,loading:m["default"].PropTypes.bool,className:m["default"].PropTypes.string,icon:m["default"].PropTypes.string},h=function(){var e=this;this.clearButton=function(t){t.className=t.className.replace(" "+e.props.prefixCls+"-clicked","")},this.handleClick=function(){var t,n=(0,P.findDOMNode)(e);e.clearButton(n),e.clickedTimeout=setTimeout(function(){return n.className+=" "+e.props.prefixCls+"-clicked"},10),clearTimeout(e.timeout),e.timeout=setTimeout(function(){return e.clearButton(n)},500),(t=e.props).onClick.apply(t,arguments)},this.handleMouseUp=function(t){(0,P.findDOMNode)(e).blur(),e.props.onMouseUp&&e.props.onMouseUp(t)}},d);t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(91),h=n(44),y=r(h),v=n(43),m=y["default"].Option,g=(c=u=function(e){function t(){var n,r,o;i(this,t);for(var s=arguments.length,l=Array(s),u=0;u<s;u++)l[u]=arguments[u];return n=r=a(this,e.call.apply(e,[this].concat(l))),r.onYearChange=function(e){var t=r.props.value.clone();t.setYear(parseInt(e,10)),r.props.onValueChange(t)},r.onMonthChange=function(e){var t=r.props.value.clone();t.setMonth(parseInt(e,10)),r.props.onValueChange(t)},r.onTypeChange=function(e){r.props.onTypeChange(e.target.value)},o=n,a(r,o)}return s(t,e),t.prototype.getYearSelectElement=function(e){for(var t=this.props,n=t.yearSelectOffset,r=t.yearSelectTotal,o=t.locale,i=t.prefixCls,a=t.fullscreen,s=e-n,l=s+r,u="\u5e74"===o.year?"\u5e74":"",c=[],p=s;p<l;p++)c.push(f["default"].createElement(m,{key:""+p},p+u));return f["default"].createElement(y["default"],{size:a?null:"small",dropdownMatchSelectWidth:!1,className:i+"-year-select",onChange:this.onYearChange,value:String(e)},c)},t.prototype.getMonthSelectElement=function(e){for(var t=this.props,n=t.locale.format.months,r=t.prefixCls,o=t.fullscreen,i=[],a=0;a<12;a++)i.push(f["default"].createElement(m,{key:""+a},n[a]));return f["default"].createElement(y["default"],{size:o?null:"small",dropdownMatchSelectWidth:!1,className:r+"-month-select",value:String(e),onChange:this.onMonthChange},i)},t.prototype.render=function(){var e=this.props,t=e.type,n=e.value,r=e.prefixCls,o=e.locale,i=e.fullscreen,a=this.getYearSelectElement(n.getYear()),s="date"===t?this.getMonthSelectElement(n.getMonth()):null,l=i?"default":"small",u=f["default"].createElement(v.Group,{onChange:this.onTypeChange,value:t,size:l},f["default"].createElement(v.Button,{value:"date"},o.month),f["default"].createElement(v.Button,{value:"month"},o.year));return f["default"].createElement("div",{className:r+"-header"},a,s,u)},t}(f["default"].Component),u.defaultProps={prefixCls:d.PREFIX_CLS+"-header",yearSelectOffset:10,yearSelectTotal:20,onValueChange:l,onTypeChange:l},u.propTypes={value:p.PropTypes.object,locale:p.PropTypes.object,yearSelectOffset:p.PropTypes.number,yearSelectTotal:p.PropTypes.number,onValueChange:p.PropTypes.func,onTypeChange:p.PropTypes.func,prefixCls:p.PropTypes.string,selectPrefixCls:p.PropTypes.string,type:p.PropTypes.string,fullscreen:p.PropTypes.bool},c);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){return null}function u(e){return e<10?"0"+e:""+e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f,d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h=n(1),y=r(h),v=n(14),m=r(v),g=n(216),b=r(g),P=n(391),C=r(P),T=n(91),O=n(214),w=r(O),x=(p=c=function(e){function t(n){i(this,t);var r=a(this,e.call(this,n));return f.call(r),r.state={value:r.parseDateFromValue(n.value||new Date),mode:n.mode},r}return s(t,e),t.prototype.parseDateFromValue=function(e){var t=new m["default"](this.getLocale());return t.setTime(+e),t},t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:this.parseDateFromValue(e.value)})},t.prototype.render=function(){var e=this.props,t=this.state,n=t.value,r=t.mode,o=e.prefixCls,i=e.style,a=e.className,s=e.fullscreen,u="year"===r?"month":"date",c=this.getLocale(),p=a||"";return s&&(p+=" "+o+"-fullscreen"),y["default"].createElement("div",{className:p,style:i},y["default"].createElement(w["default"],{fullscreen:s,type:u,value:n,locale:c.lang,prefixCls:o,onTypeChange:this.setType,onValueChange:this.setValue}),y["default"].createElement(C["default"],d({},e,{Select:l,locale:c.lang,type:u,prefixCls:o,showHeader:!1,value:n,monthCellRender:this.monthCellRender,dateCellRender:this.dateCellRender})))},t}(y["default"].Component),c.defaultProps={monthCellRender:l,dateCellRender:l,locale:{},fullscreen:!0,prefixCls:T.PREFIX_CLS,onPanelChange:l,mode:"month"},c.propTypes={monthCellRender:h.PropTypes.func,dateCellRender:h.PropTypes.func,fullscreen:h.PropTypes.bool,locale:h.PropTypes.object,prefixCls:h.PropTypes.string,className:h.PropTypes.string,style:h.PropTypes.object,onPanelChange:h.PropTypes.func,value:h.PropTypes.instanceOf(Date)},c.contextTypes={antLocale:h.PropTypes.object},f=function(){var e=this;this.getLocale=function(){var t=e.props,n=b["default"],r=e.context;r&&r.antLocale&&r.antLocale.Calendar&&(n=r.antLocale.Calendar);var o=d({},n,t.locale);return o.lang=d({},n.lang,t.locale.lang),o},this.monthCellRender=function(t,n){var r=e.props.prefixCls,o=t.getMonth();return y["default"].createElement("div",{className:r+"-month"},y["default"].createElement("div",{className:r+"-value"},n.format.shortMonths[o]),y["default"].createElement("div",{className:r+"-content"},e.props.monthCellRender(t)))},this.dateCellRender=function(t){var n=e.props.prefixCls;return y["default"].createElement("div",{className:n+"-date"},y["default"].createElement("div",{className:n+"-value"},u(t.getDayOfMonth())),y["default"].createElement("div",{className:n+"-content"},e.props.dateCellRender(t)))},this.setValue=function(t){"value"in e.props||e.state.value===t||e.setState({value:t}),e.props.onPanelChange(t,e.state.mode)},this.setType=function(t){var n="date"===t?"month":"year";e.state.mode!==n&&(e.setState({mode:n}),e.props.onPanelChange(e.state.value,n))}},p);t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(93)},function(e,t,n){"use strict";n(3),n(522),n(45),n(61)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(2),c=r(u);t["default"]=function(e){var t,n=e.prefixCls,r=void 0===n?"ant-card":n,s=e.className,u=e.children,p=e.extra,f=e.bodyStyle,d=e.title,h=e.loading,y=e.bordered,v=void 0===y||y,m=i(e,["prefixCls","className","children","extra","bodyStyle","title","loading","bordered"]),g=(0,c["default"])((t={},o(t,r,!0),o(t,s,!!s),o(t,r+"-loading",h),o(t,r+"-bordered",v),t));h&&(u=l["default"].createElement("div",null,l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588")));var b=d?l["default"].createElement("div",{className:r+"-head"},l["default"].createElement("h3",{className:r+"-head-title"},d)):null;return l["default"].createElement("div",a({},m,{className:g}),b,p?l["default"].createElement("div",{className:r+"-extra"},p):null,l["default"].createElement("div",{className:r+"-body",style:f},u))},e.exports=t["default"]},[557,523],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(506),f=r(p),d=n(1),h=r(d);if("undefined"!=typeof window){var y=function(){return{matches:!1,addListener:function(){},removeListener:function(){}}};window.matchMedia=window.matchMedia||y}var v=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=c({},this.props);"fade"===e.effect&&(e.fade=!0,e.draggable=!1); var t="ant-carousel";return e.vertical&&(t+=" ant-carousel-vertical"),h["default"].createElement("div",{className:t},h["default"].createElement(f["default"],e))},t}(h["default"].Component),l.defaultProps={dots:!0,arrows:!1,pauseOnHover:!0},u);t["default"]=v,e.exports=t["default"]},[557,524],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f,d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h=n(1),y=r(h),v=n(403),m=r(v),g=n(98),b=r(g),P=n(6),C=r(P),T=n(86),O=r(T),w=n(2),x=r(w),E=n(27),S=r(E),k=(p=c=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));f.call(r);var o=void 0;return"value"in n?o=n.value:"defaultValue"in n&&(o=n.defaultValue),r.state={value:o||[],popupVisible:!1},r}return u(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value||[]})},t.prototype.getLabel=function(){var e=this,t=this.props,n=t.options,r=t.displayRender,o=(0,O["default"])(n,function(t,n){return t.value===e.state.value[n]}),i=o.map(function(e){return e.label});return r(i,o)},t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.children,s=n.placeholder,l=n.size,u=n.disabled,c=n.className,p=n.style,f=n.allowClear,h=a(n,["prefixCls","children","placeholder","size","disabled","className","style","allowClear"]),v=(0,x["default"])({"ant-input-lg":"large"===l,"ant-input-sm":"small"===l}),g=f&&!u&&this.state.value.length>0?y["default"].createElement(C["default"],{type:"cross-circle",className:r+"-picker-clear",onClick:this.clearSelection}):null,P=(0,x["default"])((e={},i(e,r+"-picker-arrow",!0),i(e,r+"-picker-arrow-expand",this.state.popupVisible),e)),T=(0,x["default"])((t={},i(t,c,!!c),i(t,r+"-picker",!0),i(t,r+"-picker-disabled",u),t)),O=(0,S["default"])(h,["onChange","options","popupPlacement","transitionName","displayRender","onPopupVisibleChange","changeOnSelect","expandTrigger","popupVisible","getPopupContainer","loadData","popupClassName"]);return y["default"].createElement(m["default"],d({},n,{value:this.state.value,popupVisible:this.state.popupVisible,onPopupVisibleChange:this.handlePopupVisibleChange,onChange:this.handleChange}),o||y["default"].createElement("span",{style:p,className:T},y["default"].createElement(b["default"],d({},O,{placeholder:this.state.value&&this.state.value.length>0?null:s,className:r+"-input "+v,value:null,disabled:u,readOnly:!0})),y["default"].createElement("span",{className:r+"-picker-label"},this.getLabel()),g,y["default"].createElement(C["default"],{type:"down",className:P})))},t}(y["default"].Component),c.defaultProps={prefixCls:"ant-cascader",placeholder:"Please select",transitionName:"slide-up",popupPlacement:"bottomLeft",onChange:function(){},options:[],displayRender:function(e){return e.join(" / ")},disabled:!1,allowClear:!0,onPopupVisibleChange:function(){}},f=function(){var e=this;this.handleChange=function(t,n){e.setValue(t,n)},this.handlePopupVisibleChange=function(t){e.setState({popupVisible:t}),e.props.onPopupVisibleChange(t)},this.setValue=function(t){var n=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];"value"in e.props||e.setState({value:t}),e.props.onChange(t,n)},this.clearSelection=function(t){t.preventDefault(),t.stopPropagation(),e.setValue([]),e.setState({popupVisible:!1})}},p);t["default"]=k,e.exports=t["default"]},[558,525],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p,f=n(1),d=r(f),h=n(34),y=r(h),v=n(21),m=r(v),g=(c=u=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));p.call(r);var o=void 0;return"value"in n?o=n.value||[]:"defaultValue"in n&&(o=n.defaultValue||[]),r.state={value:o},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value||[]})},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return m["default"].shouldComponentUpdate.apply(this,t)},t.prototype.getOptions=function(){var e=this.props.options;return e.map(function(e){return"string"==typeof e?{label:e,value:e}:e})},t.prototype.render=function(){var e=this,t=this.getOptions();return d["default"].createElement("div",{className:"ant-checkbox-group"},t.map(function(t){return d["default"].createElement(y["default"],{disabled:"disabled"in t?t.disabled:e.props.disabled,checked:e.state.value.indexOf(t.value)!==-1,onChange:function(){return e.toggleOption(t)},className:"ant-checkbox-group-item",key:t.value},t.label)}))},t}(d["default"].Component),u.defaultProps={options:[],defaultValue:[],onChange:function(){}},u.propTypes={defaultValue:d["default"].PropTypes.array,value:d["default"].PropTypes.array,options:d["default"].PropTypes.array.isRequired,onChange:d["default"].PropTypes.func},p=function(){var e=this;this.toggleOption=function(t){var n=e.state.value.indexOf(t.value),r=[].concat(i(e.state.value));n===-1?r.push(t.value):r.splice(n,1),"value"in e.props||e.setState({value:r}),e.props.onChange(r)}},c);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(85)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(408),p=r(c),f=n(1),d=r(f),h=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return d["default"].createElement(p["default"],this.props)},t}(d["default"].Component),l.Panel=p["default"].Panel,l.defaultProps={prefixCls:"ant-collapse"},u);t["default"]=h,e.exports=t["default"]},[557,527],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(145),d=r(f),h=n(144),y=r(h),v=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(y["default"],this.props)},t}(p["default"].Component),l.defaultProps={locale:d["default"],prefixCls:"ant-calendar"},u);t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(14),y=r(h),v=n(392),m=r(v),g=n(138),b=r(g),P=n(2),C=r(P),T=n(6),O=r(T),w=(u=l=function(e){function t(n){i(this,t);var r=a(this,e.call(this,n));c.call(r);var o=r.props,s=o.value,l=o.defaultValue,u=o.parseDateFromValue,p=s&&s[0]||l[0],f=s&&s[1]||l[1];return r.state={value:[u(p),u(f)]},r}return s(t,e),t.prototype.componentWillReceiveProps=function(e){if("value"in e){var t=e.value||[],n=e.parseDateFromValue(t[0]),r=e.parseDateFromValue(t[1]);this.setState({value:[n,r]})}},t.prototype.render=function(){var e=this.props,t=e.locale,n=new y["default"](t);n.setTime(Date.now());var r=this.props,o=r.disabledDate,i=r.showTime,a=r.getCalendarContainer,s=r.transitionName,l=r.disabled,u=r.popupStyle,c=r.align,f=r.style,h=r.onOk,v=this.state,g=(0,C["default"])({"ant-calendar-time":i}),P={onChange:this.handleChange},T={onOk:this.handleChange};e.timePicker?P={}:T={};var w="startPlaceholder"in this.props?e.startPlaceholder:t.lang.rangePlaceholder[0],x="endPlaceholder"in e?e.endPlaceholder:t.lang.rangePlaceholder[1],E=d["default"].createElement(m["default"],p({prefixCls:"ant-calendar",className:g,timePicker:e.timePicker,disabledDate:o,dateInputPlaceholder:[w,x],locale:t.lang,onOk:h,defaultValue:[n,n]},T)),S=!e.disabled&&v.value&&(v.value[0]||v.value[1])?d["default"].createElement(O["default"],{type:"cross-circle",className:"ant-calendar-picker-clear",onClick:this.clearSelection}):null;return d["default"].createElement("span",{className:e.pickerClass,style:f},d["default"].createElement(b["default"],p({formatter:e.getFormatter(),transitionName:s,disabled:l,calendar:E,value:v.value,prefixCls:"ant-calendar-picker-container",style:u,align:c,getCalendarContainer:a,onOpen:e.toggleOpen,onClose:e.toggleOpen},P),function(t){var n=t.value,r=n[0],o=n[1];return d["default"].createElement("span",{className:e.pickerInputClass,disabled:l},d["default"].createElement("input",{disabled:l,readOnly:!0,value:r?e.getFormatter().format(r):"",placeholder:w,className:"ant-calendar-range-picker-input"}),d["default"].createElement("span",{className:"ant-calendar-range-picker-separator"}," ~ "),d["default"].createElement("input",{disabled:l,readOnly:!0,value:o?e.getFormatter().format(o):"",placeholder:x,className:"ant-calendar-range-picker-input"}),S,d["default"].createElement("span",{className:"ant-calendar-picker-icon"}))}))},t}(d["default"].Component),l.defaultProps={defaultValue:[]},c=function(){var e=this;this.clearSelection=function(t){t.preventDefault(),t.stopPropagation(),e.setState({value:[]}),e.handleChange([])},this.handleChange=function(t){var n=e.props;"value"in n||e.setState({value:t});var r=t[0]?new Date(t[0].getTime()):null,o=t[1]?new Date(t[1].getTime()):null,i=t[0]?n.getFormatter().format(t[0]):"",a=t[1]?n.getFormatter().format(t[1]):"";n.onChange([r,o],[i,a])}},u);t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(e){var t,n,r;return n=t=function(t){function n(e){i(this,n);var o=a(this,t.call(this,e));return r.call(o),o.state={value:o.props.parseDateFromValue(o.props.value||o.props.defaultValue)},o}return s(n,t),n.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.parseDateFromValue(e.value)})},n.prototype.render=function(){var t=this,n=this.props,r=n.locale,o=new m["default"](r);o.setTime(Date.now());var i="placeholder"in n?n.placeholder:r.lang.placeholder,a=n.showTime?n.disabledTime:null,s=(0,b["default"])({"ant-calendar-time":n.showTime,"ant-calendar-month":d["default"]===e}),l={onChange:this.handleChange},c={onOk:this.handleChange,onSelect:function(e,n){n&&"todayButton"===n.source&&t.handleChange(e)}};n.showTime?l={}:c={};var f=p["default"].createElement(e,u({formatter:n.getFormatter(),disabledDate:n.disabledDate,disabledTime:a,locale:r.lang,timePicker:n.timePicker,defaultValue:o,dateInputPlaceholder:i,prefixCls:"ant-calendar",className:s,onOk:n.onOk},c)),h={};n.showTime&&(h.width=180);var v=!n.disabled&&this.state.value?p["default"].createElement(C["default"],{type:"cross-circle",className:"ant-calendar-picker-clear",onClick:this.clearSelection}):null;return p["default"].createElement("span",{className:n.pickerClass,style:u({},h,n.style)},p["default"].createElement(y["default"],u({transitionName:n.transitionName,disabled:n.disabled,calendar:f,value:this.state.value,prefixCls:"ant-calendar-picker-container",style:n.popupStyle,align:n.align,getCalendarContainer:n.getCalendarContainer,open:n.open,onOpen:n.toggleOpen,onClose:n.toggleOpen},l),function(e){var t=e.value;return p["default"].createElement("span",null,p["default"].createElement("input",{disabled:n.disabled,readOnly:!0,value:t?n.getFormatter().format(t):"",placeholder:i,className:n.pickerInputClass}),v,p["default"].createElement("span",{className:"ant-calendar-picker-icon"}))}))},n}(p["default"].Component),r=function(){var e=this;this.clearSelection=function(t){t.preventDefault(),t.stopPropagation(),e.setState({value:null}),e.handleChange(null)},this.handleChange=function(t){var n=e.props;"value"in n||e.setState({value:t});var r=t?new Date(t.getTime()):null;n.onChange(r,t?n.getFormatter().format(t):"")}},n}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=l;var c=n(1),p=r(c),f=n(137),d=r(f),h=n(138),y=r(h),v=n(14),m=r(v),g=n(2),b=r(g),P=n(6),C=r(P);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(144),i=r(o),a=n(137),s=r(a),l=n(230),u=r(l),c=n(233),p=r(c),f=n(229),d=r(f),h=n(228),y=r(h),v=(0,p["default"])((0,u["default"])(i["default"])),m=(0,p["default"])((0,u["default"])(s["default"]),"yyyy-MM");v.Calendar=y["default"],v.RangePicker=(0,p["default"])(d["default"],"yyyy-MM-dd"),v.MonthPicker=m,t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(528),n(23),n(112)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(e,t){var n,r;return r=n=function(t){function n(){var e,r,o;i(this,n);for(var s=arguments.length,l=Array(s),u=0;u<s;u++)l[u]=arguments[u];return e=r=a(this,t.call.apply(t,[this].concat(l))),r.getFormatter=function(){var e=r.props.format,t=new y["default"](e,r.getLocale().lang.format);return t},r.parseDateFromValue=function(e){if(e){if("string"==typeof e)return r.getFormatter().parse(e,{locale:r.getLocale()});if(e instanceof Date){var t=new m["default"](r.getLocale());return t.setTime(+e),t}}return e},r.toggleOpen=function(e){var t=e.open;r.props.toggleOpen({open:t})},o=e,a(r,o)}return s(n,t),n.prototype.getLocale=function(){var e=this.props,t=C["default"],n=this.context;n.antLocale&&n.antLocale.DatePicker&&(t=n.antLocale.DatePicker);var r=u({},t,e.locale);return r.lang=u({},t.lang,e.locale.lang),r},n.prototype.render=function(){var t=this.props,n=(0,b["default"])({"ant-calendar-picker":!0}),r=(0,b["default"])({"ant-calendar-range-picker":!0,"ant-input":!0,"ant-input-lg":"large"===t.size,"ant-input-sm":"small"===t.size}),o=this.getLocale(),i=t.showTime&&t.showTime.format,a={formatter:new y["default"](i||"HH:mm:ss",o.timePickerLocale.format),showSecond:i&&i.indexOf("ss")>=0,showHour:i&&i.indexOf("HH")>=0},s=t.showTime?p["default"].createElement(d["default"],u({},a,t.showTime,{prefixCls:"ant-time-picker",placeholder:o.timePickerLocale.placeholder,locale:o.timePickerLocale,transitionName:"slide-up"})):null;return p["default"].createElement(e,u({},t,{pickerClass:n,pickerInputClass:r,locale:o,timePicker:s,toggleOpen:this.toggleOpen,getFormatter:this.getFormatter,parseDateFromValue:this.parseDateFromValue}))},n}(p["default"].Component),n.defaultProps={format:t||"yyyy-MM-dd",transitionName:"slide-up",popupStyle:{},onChange:function(){},onOk:function(){},toggleOpen:function(){},locale:{},align:{offset:[0,-9]}},n.contextTypes={antLocale:c.PropTypes.object},r}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=l;var c=n(1),p=r(c),f=n(474),d=r(f),h=n(53),y=r(h),v=n(14),m=r(v),g=n(2),b=r(g),P=n(93),C=r(P);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(29),v=r(y),m=n(6),g=r(m),b=n(94),P=r(b),C=n(2),T=r(C),O=v["default"].Group,w=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e=this.props,t=e.type,n=e.overlay,r=e.trigger,o=e.align,s=e.children,l=e.className,u=e.onClick,c=a(e,["type","overlay","trigger","align","children","className","onClick"]),p=(0,T["default"])(i({"ant-dropdown-button":!0},l,!!l));return h["default"].createElement(O,f({},c,{className:p}),h["default"].createElement(v["default"],{type:t,onClick:u},s),h["default"].createElement(P["default"],{align:o,overlay:n,trigger:r},h["default"].createElement(v["default"],{type:t},h["default"].createElement(g["default"],{type:"down"}))))},t}(h["default"].Component),c.defaultProps={align:{points:["tr","br"],overlay:{adjustX:1,adjustY:1},offset:[0,4],targetOffset:[0,0]},type:"default"},p);t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(2),y=r(h),v=n(21),m=r(v),g=n(27),b=r(g),P=n(22),C=r(P),T=(c=u=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return(0,C["default"])(!n.form,"It is unnecessary to pass `form` to `Form` after antd@1.7.0."),r}return l(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return m["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.inline,a=t.horizontal,s=(0,y["default"])((e={},i(e,""+n,!0),i(e,n+"-horizontal",a),i(e,n+"-inline",o),i(e,r,!!r),e)),l=(0,b["default"])(this.props,["prefixCls","className","inline","horizontal","form"]);return d["default"].createElement("form",p({},l,{className:s}))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-form",onSubmit:function(e){e.preventDefault()}},u.propTypes={prefixCls:d["default"].PropTypes.string,horizontal:d["default"].PropTypes.bool,inline:d["default"].PropTypes.bool,children:d["default"].PropTypes.any,onSubmit:d["default"].PropTypes.func},c);t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(2),y=r(h),v=n(21),m=r(v),g=n(108),b=r(g),P=n(92),C=r(P),T=n(97),O=(c=u=function(e){function t(){return a(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return m["default"].shouldComponentUpdate.apply(this,t)},t.prototype.getHelpMsg=function(){var e=this.context,t=this.props;return void 0===t.help&&e.form?this.getId()?(e.form.getFieldError(this.getId())||[]).join(", "):"":t.help},t.prototype.getOnlyControl=function(){var e=d["default"].Children.toArray(this.props.children),t=e.filter(function(e){return e.props&&T.FIELD_META_PROP in e.props})[0];return void 0!==t?t:null},t.prototype.getChildProp=function(e){var t=this.getOnlyControl();return t&&t.props&&t.props[e]},t.prototype.getId=function(){return this.getChildProp("id")},t.prototype.getMeta=function(){return this.getChildProp(T.FIELD_META_PROP)},t.prototype.renderHelp=function(){var e=this.props.prefixCls,t=this.getHelpMsg();return t?d["default"].createElement("div",{className:e+"-explain",key:"help"},t):null},t.prototype.renderExtra=function(){var e=this.props,t=e.prefixCls,n=e.extra;return n?d["default"].createElement("span",{className:t+"-extra"},n):null},t.prototype.getValidateStatus=function(){var e=this.context.form,t=e.isFieldValidating,n=e.getFieldError,r=e.getFieldValue,o=this.getId();return o?t(o)?"validating":n(o)?"error":void 0!==r(o)?"success":"":""},t.prototype.renderValidateWrapper=function(e,t,n){var r="",o=this.context.form,i=this.props,a=void 0===i.validateStatus&&o?this.getValidateStatus():i.validateStatus;return a&&(r=(0,y["default"])({"has-feedback":i.hasFeedback,"has-success":"success"===a,"has-warning":"warning"===a,"has-error":"error"===a,"is-validating":"validating"===a})),d["default"].createElement("div",{className:this.props.prefixCls+"-item-control "+r},e,t,n)},t.prototype.renderWrapper=function(e){var t=this.props.wrapperCol;return d["default"].createElement(C["default"],p({},t,{key:"wrapper"}),e)},t.prototype.isRequired=function(){if(this.context.form){var e=this.getMeta()||{},t=e.validate||[];return t.filter(function(e){return!!e.rules}).some(function(e){return e.rules.some(function(e){return e.required})})}return!1},t.prototype.renderLabel=function(){var e=this.props,t=e.labelCol,n=void 0===e.required?this.isRequired():e.required,r=(0,y["default"])(i({},e.prefixCls+"-item-required",n)),o=e.label;return"string"==typeof o&&""!==o.trim()&&(o=e.label.replace(/[\uff1a|:]\s*$/,"")),e.label?d["default"].createElement(C["default"],p({},t,{key:"label",className:e.prefixCls+"-item-label"}),d["default"].createElement("label",{htmlFor:e.id||this.getId(),className:r},o)):null},t.prototype.renderChildren=function(){var e=this.props,t=d["default"].Children.map(e.children,function(e){return e&&"function"==typeof e.type&&!e.props.size?d["default"].cloneElement(e,{size:"large"}):e});return[this.renderLabel(),this.renderWrapper(this.renderValidateWrapper(t,this.renderHelp(),this.renderExtra()))]},t.prototype.renderFormItem=function(e){var t,n=this.props,r=n.prefixCls,o=n.style,a=(t={},i(t,r+"-item",!0),i(t,r+"-item-with-help",!!this.getHelpMsg()),i(t,""+n.className,!!n.className),t);return d["default"].createElement(b["default"],{className:(0,y["default"])(a),style:o},e)},t.prototype.render=function(){var e=this.renderChildren();return this.renderFormItem(e)},t}(d["default"].Component),u.defaultProps={hasFeedback:!1,prefixCls:"ant-form"},u.propTypes={prefixCls:d["default"].PropTypes.string,label:d["default"].PropTypes.node,labelCol:d["default"].PropTypes.object,help:d["default"].PropTypes.oneOfType([d["default"].PropTypes.node,d["default"].PropTypes.bool]),validateStatus:d["default"].PropTypes.oneOf(["","success","warning","error","validating"]),hasFeedback:d["default"].PropTypes.bool,wrapperCol:d["default"].PropTypes.object,className:d["default"].PropTypes.string,id:d["default"].PropTypes.string,children:d["default"].PropTypes.node},u.contextTypes={form:d["default"].PropTypes.object},c);t["default"]=O,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},r={setValue:function(e,t){var r=t,o=t&&t.target;o&&(r="input"===(""+o.nodeName).toLowerCase()&&"checkbox"===o.type?o.checked:t.target.value);var i={};i[e]=r,this.setState({formData:n({},this.state.formData,i)})}};t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(417),l=r(s),u=n(235),c=r(u),p=n(236),f=r(p),d=n(237),h=r(d),y=n(97);c["default"].create=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=o({},e,{fieldNameProp:"id",fieldMetaProp:y.FIELD_META_PROP}),n=(0,l["default"])(t);return function(e){return n(a["default"].createClass({propTypes:{form:i.PropTypes.object.isRequired},childContextTypes:{form:i.PropTypes.object.isRequired},getChildContext:function(){return{form:this.props.form}},render:function(){return a["default"].createElement(e,this.props)}}))}},c["default"].Item=f["default"], c["default"].ValueMixin=h["default"],t["default"]=c["default"],e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(530),n(99)},function(e,t,n){"use strict";n(3)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=n(419),g=r(m),b=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.className,r=t.size,o=a(t,["className","size"]),s=(0,v["default"])((e={},i(e,this.props.prefixCls+"-lg","large"===r),i(e,this.props.prefixCls+"-sm","small"===r),i(e,n,!!n),e));return h["default"].createElement(g["default"],f({className:s},o))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-input-number",step:1},p);t["default"]=b,e.exports=t["default"]},[557,531],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=(0,u["default"])(o({"ant-input-group":!0,"ant-input-group-lg":"large"===e.size,"ant-input-group-sm":"small"===e.size},e.className,!!e.className));return s["default"].createElement("span",{className:t,style:e.style},e.children)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=i;var a=n(1),s=r(a),l=n(2),u=r(l);i.propTypes={children:s["default"].PropTypes.any},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}function u(e){return"undefined"==typeof e||null===e?"":e}function c(e){return window.requestAnimationFrame?window.requestAnimationFrame(e):window.setTimeout(e,1)}function p(e){window.cancelAnimationFrame?window.cancelAnimationFrame(e):window.clearTimeout(e)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var f,d,h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},y=n(1),v=r(y),m=n(2),g=r(m),b=n(245),P=r(b),C=n(27),T=r(C),O=(d=f=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return r.handleKeyDown=function(e){13===e.keyCode&&r.props.onPressEnter(e),r.props.onKeyDown(e)},r.handleTextareaChange=function(e){"value"in r.props||r.resizeTextarea(),r.props.onChange(e)},r.resizeTextarea=function(){var e=r.props,t=e.type,n=e.autosize;if("textarea"===t&&n&&r.refs.input){var o=n?n.minRows:null,i=n?n.maxRows:null,a=(0,P["default"])(r.refs.input,!1,o,i);r.setState({textareaStyles:a})}},r.state={textareaStyles:null},r}return l(t,e),t.prototype.componentDidMount=function(){this.resizeTextarea()},t.prototype.componentWillReceiveProps=function(e){this.props.value!==e.value&&(this.nextFrameActionId&&p(this.nextFrameActionId),this.nextFrameActionId=c(this.resizeTextarea))},t.prototype.renderLabledInput=function(e){var t,n=this.props,r=n.prefixCls+"-group",o=r+"-addon",a=n.addonBefore?v["default"].createElement("span",{className:o},n.addonBefore):null,s=n.addonAfter?v["default"].createElement("span",{className:o},n.addonAfter):null,l=(0,g["default"])((t={},i(t,n.prefixCls+"-wrapper",!0),i(t,r,a||s),t));return v["default"].createElement("span",{className:l},a,e,s)},t.prototype.renderInput=function(){var e,t=h({},this.props),n=(0,T["default"])(this.props,["prefixCls","onPressEnter","autosize","addonBefore","addonAfter"]),r=t.prefixCls;if(!t.type)return t.children;var o=(0,g["default"])((e={},i(e,r,!0),i(e,r+"-sm","small"===t.size),i(e,r+"-lg","large"===t.size),i(e,t.className,!!t.className),e));switch("value"in t&&(n.value=u(t.value),delete n.defaultValue),t.type){case"textarea":return v["default"].createElement("textarea",h({},n,{style:h({},t.style,this.state.textareaStyles),className:o,onKeyDown:this.handleKeyDown,onChange:this.handleTextareaChange,ref:"input"}));default:return v["default"].createElement("input",h({},n,{className:o,onKeyDown:this.handleKeyDown,ref:"input"}))}},t.prototype.render=function(){return this.renderLabledInput(this.renderInput())},t}(y.Component),f.defaultProps={defaultValue:"",disabled:!1,prefixCls:"ant-input",type:"text",onPressEnter:function(){},onKeyDown:function(){},onChange:function(){},autosize:!1},f.propTypes={type:y.PropTypes.string,id:y.PropTypes.oneOfType([y.PropTypes.string,y.PropTypes.number]),size:y.PropTypes.oneOf(["small","default","large"]),disabled:y.PropTypes.bool,value:y.PropTypes.any,defaultValue:y.PropTypes.any,className:y.PropTypes.string,addonBefore:y.PropTypes.node,addonAfter:y.PropTypes.node,prefixCls:y.PropTypes.string,autosize:y.PropTypes.oneOfType([y.PropTypes.bool,y.PropTypes.object]),onPressEnter:y.PropTypes.func,onKeyDown:y.PropTypes.func},d);t["default"]=O,e.exports=t["default"]},function(e,t){"use strict";function n(e){var t=!(arguments.length<=1||void 0===arguments[1])&&arguments[1],n=e.getAttribute("id")||e.getAttribute("data-reactid")||e.getAttribute("name");if(t&&a[n])return a[n];var r=window.getComputedStyle(e),o=r.getPropertyValue("box-sizing")||r.getPropertyValue("-moz-box-sizing")||r.getPropertyValue("-webkit-box-sizing"),s=parseFloat(r.getPropertyValue("padding-bottom"))+parseFloat(r.getPropertyValue("padding-top")),l=parseFloat(r.getPropertyValue("border-bottom-width"))+parseFloat(r.getPropertyValue("border-top-width")),u=i.map(function(e){return e+":"+r.getPropertyValue(e)}).join(";"),c={sizingStyle:u,paddingSize:s,borderSize:l,boxSizing:o};return t&&n&&(a[n]=c),c}function r(e){var t=!(arguments.length<=1||void 0===arguments[1])&&arguments[1],r=arguments.length<=2||void 0===arguments[2]?null:arguments[2],i=arguments.length<=3||void 0===arguments[3]?null:arguments[3];s||(s=document.createElement("textarea"),document.body.appendChild(s));var a=n(e,t),l=a.paddingSize,u=a.borderSize,c=a.boxSizing,p=a.sizingStyle;s.setAttribute("style",p+";"+o),s.value=e.value||e.placeholder||"";var f=-(1/0),d=1/0,h=s.scrollHeight;if("border-box"===c?h+=u:"content-box"===c&&(h-=l),null!==r||null!==i){s.value="";var y=s.scrollHeight-l;null!==r&&(f=y*r,"border-box"===c&&(f=f+l+u),h=Math.max(f,h)),null!==i&&(d=y*i,"border-box"===c&&(d=d+l+u),h=Math.min(d,h))}return{height:h,minHeight:f,maxHeight:d}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var o="\n min-height:0 !important;\n max-height:none !important;\n height:0 !important;\n visibility:hidden !important;\n overflow:hidden !important;\n position:absolute !important;\n z-index:-1000 !important;\n top:0 !important;\n right:0 !important\n",i=["letter-spacing","line-height","padding-top","padding-bottom","font-family","font-weight","font-size","text-rendering","text-transform","width","text-indent","padding-left","padding-right","border-width","box-sizing"],a={},s=void 0;e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e){var t,n=e.span,r=e.order,a=e.offset,u=e.push,p=e.pull,d=e.className,h=e.children,y=i(e,["span","order","offset","push","pull","className","children"]),v={};["xs","sm","md","lg"].forEach(function(t){var n,r={};"number"==typeof e[t]?r.span=e[t]:"object"===l(e[t])&&(r=e[t]||{}),delete y[t],v=s({},v,(n={},o(n,"ant-col-"+t+"-"+r.span,void 0!==r.span),o(n,"ant-col-"+t+"-order-"+r.order,r.order),o(n,"ant-col-"+t+"-offset-"+r.offset,r.offset),o(n,"ant-col-"+t+"-push-"+r.push,r.push),o(n,"ant-col-"+t+"-pull-"+r.pull,r.pull),n))});var m=(0,f["default"])(s((t={},o(t,"ant-col-"+n,void 0!==n),o(t,"ant-col-order-"+r,r),o(t,"ant-col-offset-"+a,a),o(t,"ant-col-push-"+u,u),o(t,"ant-col-pull-"+p,p),o(t,d,!!d),t),v));return c["default"].createElement("div",s({},y,{className:m}),h)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t["default"]=a;var u=n(1),c=r(u),p=n(2),f=r(p),d=u.PropTypes.oneOfType([u.PropTypes.string,u.PropTypes.number]),h=u.PropTypes.oneOfType([u.PropTypes.object,u.PropTypes.number]);a.propTypes={span:d,order:d,offset:d,push:d,pull:d,className:u.PropTypes.string,children:u.PropTypes.node,xs:h,sm:h,md:h,lg:h},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.type,r=t.justify,o=t.align,s=t.className,l=t.gutter,u=t.style,c=t.children,p=a(t,["type","justify","align","className","gutter","style","children"]),y=(0,v["default"])((e={"ant-row":!n},i(e,"ant-row-"+n,n),i(e,"ant-row-"+n+"-"+r,r),i(e,"ant-row-"+n+"-"+o,o),i(e,s,s),e)),m=l>0?f({marginLeft:l/-2,marginRight:l/-2},u):u,g=d.Children.map(c,function(e){return e?e.props?(0,d.cloneElement)(e,{style:l>0?f({paddingLeft:l/2,paddingRight:l/2},e.props.style):e.props.style}):e:null});return h["default"].createElement("div",f({},p,{className:y,style:m}),g)},t}(h["default"].Component),c.defaultProps={gutter:0},c.propTypes={type:h["default"].PropTypes.string,align:h["default"].PropTypes.string,justify:h["default"].PropTypes.string,className:h["default"].PropTypes.string,children:h["default"].PropTypes.node,gutter:h["default"].PropTypes.number},p);t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(101),d=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.getChildContext=function(){return{antLocale:this.props.locale}},t.prototype.componentDidMount=function(){this.componentDidUpdate()},t.prototype.componentDidUpdate=function(){var e=this.props.locale;(0,f.changeConfirmLocale)(e&&e.Modal)},t.prototype.componentWillUnMount=function(){(0,f.changeConfirmLocale)()},t.prototype.render=function(){return p["default"].Children.only(this.props.children)},t}(p["default"].Component),l.propTypes={locale:p["default"].PropTypes.object},l.childContextTypes={antLocale:p["default"].PropTypes.object},u);t["default"]=d,e.exports=t["default"]},function(e,t){"use strict"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(40),y=r(h),v=n(89),m=r(v),g=(c=u=function(e){function t(n){i(this,t);var r=a(this,e.call(this,n));return r.handleClick=function(e){r.setOpenKeys([]),r.props.onClick(e)},r.handleOpenKeys=function(e){var t=e.openKeys;r.setOpenKeys(t),r.props.onOpen(e)},r.handleCloseKeys=function(e){var t=e.openKeys;r.setOpenKeys(t),r.props.onClose(e)},r.state={openKeys:[]},r}return s(t,e),t.prototype.componentWillReceiveProps=function(e){"inline"===this.props.mode&&"inline"!==e.mode&&(this.switchModeFromInline=!0),"openKeys"in e&&this.setOpenKeys(e.openKeys)},t.prototype.setOpenKeys=function(e){"openKeys"in this.props||this.setState({openKeys:e})},t.prototype.render=function(){var e=this.props.openAnimation||this.props.openTransitionName;if(!e)switch(this.props.mode){case"horizontal":e="slide-up";break;case"vertical":this.switchModeFromInline?(e="",this.switchModeFromInline=!1):e="zoom-big";break;case"inline":e=m["default"]}var t={},n=this.props.className+" "+this.props.prefixCls+"-"+this.props.theme;return t="inline"!==this.props.mode?{openKeys:this.state.openKeys,onClick:this.handleClick,onOpen:this.handleOpenKeys,onClose:this.handleCloseKeys,openTransitionName:e,className:n}:{openAnimation:e,className:n},d["default"].createElement(y["default"],p({},this.props,t))},t}(d["default"].Component),u.Divider=h.Divider,u.Item=h.Item,u.SubMenu=h.SubMenu,u.ItemGroup=h.ItemGroup,u.defaultProps={prefixCls:"ant-menu",onClick:l,onOpen:l,onClose:l,className:"",theme:"light"},c);t["default"]=g,e.exports=t["default"]},[557,533],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){return h=h||u["default"].newInstance({prefixCls:v,transitionName:"move-up",style:{top:d}})}function i(e){var t=arguments.length<=1||void 0===arguments[1]?f:arguments[1],n=arguments[2],r=arguments[3],i={info:"info-circle",success:"check-circle",error:"cross-circle",warning:"exclamation-circle",loading:"loading"}[n],a=o();return a.notice({key:y,duration:t,style:{},content:s["default"].createElement("div",{className:v+"-custom-content "+v+"-"+n},s["default"].createElement(p["default"],{type:i}),s["default"].createElement("span",null,e)),onClose:r}),function(){var e=y++;return function(){a.removeNotice(e)}}()}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a),l=n(153),u=r(l),c=n(6),p=r(c),f=1.5,d=void 0,h=void 0,y=1,v="ant-message";t["default"]={info:function(e,t,n){return i(e,t,"info",n)},success:function(e,t,n){return i(e,t,"success",n)},error:function(e,t,n){return i(e,t,"error",n)},warn:function(e,t,n){return i(e,t,"warning",n)},warning:function(e,t,n){return i(e,t,"warning",n)},loading:function(e,t,n){return i(e,t,"loading",n)},config:function(e){"top"in e&&(d=e.top),"duration"in e&&(f=e.duration),"prefixCls"in e&&(v=e.prefixCls)},destroy:function(){h&&(h.destroy(),h=null)}},e.exports=t["default"]},[557,534],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){function t(){var e=c["default"].unmountComponentAtNode(u);e&&u.parentNode.removeChild(u)}function n(){var e=s.onCancel;if(e){var n=void 0;e.length?n=e(t):(n=e(),n||t()),n&&n.then&&n.then(t)}else t()}function r(){var e=s.onOk;if(e){var n=void 0;e.length?n=e(t):(n=e(),n||t()),n&&n.then&&n.then(t)}else t()}var i,s=a({},e),u=document.createElement("div");document.body.appendChild(u),s.iconType=s.iconType||"question-circle";var p=s.width||416,d=s.style||{};"okCancel"in s||(s.okCancel=!0);var y=(0,b.getConfirmLocale)();s.okText=s.okText||(s.okCancel?y.okText:y.justOkText),s.cancelText=s.cancelText||y.cancelText;var m=l["default"].createElement("div",{className:"ant-confirm-body"},l["default"].createElement(h["default"],{type:s.iconType}),l["default"].createElement("span",{className:"ant-confirm-title"},s.title),l["default"].createElement("div",{className:"ant-confirm-content"},s.content)),P=null;P=s.okCancel?l["default"].createElement("div",{className:"ant-confirm-btns"},l["default"].createElement(v["default"],{type:"ghost",size:"large",onClick:n},s.cancelText),l["default"].createElement(v["default"],{type:"primary",size:"large",onClick:r},s.okText)):l["default"].createElement("div",{className:"ant-confirm-btns"},l["default"].createElement(v["default"],{type:"primary",size:"large",onClick:r},s.okText));var C=(0,g["default"])((i={"ant-confirm":!0},o(i,"ant-confirm-"+s.type,!0),o(i,s.className,!!s.className),i));return c["default"].render(l["default"].createElement(f["default"],{className:C,visible:!0,closable:!1,title:"",transitionName:"zoom",footer:"",maskTransitionName:"fade",style:d,width:p},l["default"].createElement("div",{style:{zoom:1,overflow:"hidden"}},m," ",P)),u),{destroy:t}}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=i;var s=n(1),l=r(s),u=n(4),c=r(u),p=n(100),f=r(p),d=n(6),h=r(d),y=n(29),v=r(y),m=n(2),g=r(m),b=n(101);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(100),a=r(i),s=n(254),l=r(s);a["default"].info=function(e){var t=o({type:"info",iconType:"info-circle",okCancel:!1},e);return(0,l["default"])(t)},a["default"].success=function(e){var t=o({type:"success",iconType:"check-circle",okCancel:!1},e);return(0,l["default"])(t)},a["default"].error=function(e){var t=o({type:"error",iconType:"cross-circle",okCancel:!1},e);return(0,l["default"])(t)},a["default"].warning=a["default"].warn=function(e){var t=o({type:"warning",iconType:"exclamation-circle",okCancel:!1},e);return(0,l["default"])(t)},a["default"].confirm=function(e){var t=o({type:"confirm",okCancel:!0},e);return(0,l["default"])(t)},t["default"]=a["default"],e.exports=t["default"]},[559,535],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){return h?h:h=c["default"].newInstance({prefixCls:"ant-notification",style:{top:d,right:0}})}function i(e){var t=e.prefixCls||"ant-notification-notice",n=void 0;n=void 0===e.duration?y:e.duration;var r="";switch(e.icon){case"success":r="check-circle-o";break;case"info":r="info-circle-o";break;case"error":r="cross-circle-o";break;case"warning":r="exclamation-circle-o";break;default:r="info-circle"}o().notice({content:l["default"].createElement("div",{className:t+"-content "+(e.icon?t+"-with-icon":"")},e.icon?l["default"].createElement(f["default"],{className:t+"-icon "+t+"-icon-"+e.icon,type:r}):null,l["default"].createElement("div",{className:t+"-message"},e.message),l["default"].createElement("div",{className:t+"-description"},e.description),e.btn?l["default"].createElement("span",{className:t+"-btn"},e.btn):null),duration:n,closable:!0,onClose:e.onClose,key:e.key,style:{}})}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(153),c=r(u),p=n(6),f=r(p),d=24,h=void 0,y=4.5,v={open:function(e){i(e)},close:function(e){h&&h.removeNotice(e)},config:function(e){"top"in e&&(d=e.top),"duration"in e&&(y=e.duration)},destroy:function(){h&&(h.destroy(),h=null)}};["success","info","warning","error"].forEach(function(e){v[e]=function(t){return v.open(a({},t,{icon:e}))}}),v.warn=v.warning,t["default"]=v,e.exports=t["default"]},[557,536],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(44),h=r(d),y=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return f["default"].createElement(h["default"],c({size:"small"},this.props))},t}(f["default"].Component),l.Option=h["default"].Option,u);t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(434),h=r(d),y=n(44),v=r(y),m=n(259),g=r(m),b=n(261),P=r(b),C=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props.className,t=v["default"],n=void 0;return n=this.context.antLocale&&this.context.antLocale.Pagination?this.context.antLocale.Pagination:this.props.locale,"small"===this.props.size&&(e+=" mini",t=g["default"]),f["default"].createElement(h["default"],c({selectComponentClass:t,selectPrefixCls:"ant-select"},this.props,{locale:n,className:e}))},t}(f["default"].Component),l.defaultProps={locale:P["default"],className:"",prefixCls:"ant-pagination"},l.contextTypes={antLocale:f["default"].PropTypes.object},u);t["default"]=C,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(155)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(62),y=r(h),v=n(6),m=r(v),g=n(29),b=r(g),P=n(59),C=r(P),T=function(){},O=(c=u=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return r.confirm=function(){r.setVisible(!1),r.props.onConfirm.call(r)},r.cancel=function(){r.setVisible(!1),r.props.onCancel.call(r)},r.onVisibleChange=function(e){r.setVisible(e)},r.state={visible:!1},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"visible"in e&&this.setState({visible:e.visible})},t.prototype.setVisible=function(e){"visible"in this.props||this.setState({visible:e}),this.props.onVisibleChange(e)},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.title,r=e.placement,o=e.arrowPointAtCenter,a=i(e,["prefixCls","title","placement","arrowPointAtCenter"]),s=this.props,l=s.okText,u=s.cancelText;this.context.antLocale&&this.context.antLocale.Popconfirm&&(l=l||this.context.antLocale.Popconfirm.okText,u=u||this.context.antLocale.Popconfirm.cancelText);var c=d["default"].createElement("div",null,d["default"].createElement("div",{className:t+"-inner-content"},d["default"].createElement("div",{className:t+"-message"},d["default"].createElement(m["default"],{type:"exclamation-circle"}),d["default"].createElement("div",{className:t+"-message-title"},n)),d["default"].createElement("div",{className:t+"-buttons"},d["default"].createElement(b["default"],{onClick:this.cancel,type:"ghost",size:"small"},u||"\u53d6\u6d88"),d["default"].createElement(b["default"],{onClick:this.confirm,type:"primary",size:"small"},l||"\u786e\u5b9a"))));return d["default"].createElement(y["default"],p({},a,{builtinPlacements:(0,C["default"])({arrowPointAtCenter:o}),prefixCls:t,placement:r,onVisibleChange:this.onVisibleChange,visible:this.state.visible,overlay:c}))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-popover",transitionName:"zoom-big",placement:"top",trigger:"click",onConfirm:T,onCancel:T,onVisibleChange:T},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=O,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(104)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(62),h=r(d),y=n(59),v=r(y),m=n(22),g=r(m),b=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props.arrowPointAtCenter;return f["default"].createElement(h["default"],c({builtinPlacements:(0,v["default"])({arrowPointAtCenter:e}),ref:"tooltip"},this.props,{overlay:this.getOverlay()}))},t.prototype.getPopupDomNode=function(){return this.refs.tooltip.getPopupDomNode()},t.prototype.componentDidMount=function(){"overlay"in this.props&&(0,g["default"])(!1,"`overlay` prop of Popover is deprecated, use `content` instead.")},t.prototype.getOverlay=function(){var e=this.props,t=e.title,n=e.prefixCls,r=e.overlay,o=e.content; return f["default"].createElement("div",null,t&&f["default"].createElement("div",{className:n+"-title"},t),f["default"].createElement("div",{className:n+"-inner-content"},o||r))},t}(f["default"].Component),l.defaultProps={prefixCls:"ant-popover",placement:"top",transitionName:"zoom-big",trigger:"hover",mouseEnterDelay:.1,mouseLeaveDelay:.1,arrowPointAtCenter:!1},u);t["default"]=b,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(6),v=r(y),m=n(436),g=n(2),b=r(g),P={normal:"#2db7f5",exception:"#ff5500",success:"#87d068"},C=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.status,o=t.format,s=t.percent,l=t.trailColor,u=t.type,c=t.strokeWidth,p=t.width,d=t.className,y=t.showInfo,g=a(t,["prefixCls","status","format","percent","trailColor","type","strokeWidth","width","className","showInfo"]),C=parseInt(s,10)>=100&&!("status"in this.props)?"success":r||"normal",T=void 0,O=void 0,w=o||function(e){return e+"%"};if(y){var x=void 0,E="circle"===u?"":"-circle";x="exception"===C?o?w(s):h["default"].createElement(v["default"],{type:"cross"+E}):"success"===C?o?w(s):h["default"].createElement(v["default"],{type:"check"+E}):w(s),T=h["default"].createElement("span",{className:n+"-text"},x)}if("line"===u){var S={width:s+"%",height:c||10};O=h["default"].createElement("div",null,h["default"].createElement("div",{className:n+"-outer"},h["default"].createElement("div",{className:n+"-inner"},h["default"].createElement("div",{className:n+"-bg",style:S}))),T)}else if("circle"===u){var k=p||132,N={width:k,height:k,fontSize:.16*k+6};O=h["default"].createElement("div",{className:n+"-inner",style:N},h["default"].createElement(m.Circle,{percent:s,strokeWidth:c||6,strokeColor:P[C],trailColor:l}),T)}var j=(0,b["default"])((e={},i(e,""+n,!0),i(e,n+"-"+u,!0),i(e,n+"-status-"+C,!0),i(e,n+"-show-info",y),i(e,d,!!d),e));return h["default"].createElement("div",f({},g,{className:j}),O)},t}(h["default"].Component),c.defaultProps={type:"line",percent:0,showInfo:!0,trailColor:"#f3f3f3",prefixCls:"ant-progress"},c.propTypes={status:d.PropTypes.oneOf(["normal","exception","active","success"]),type:d.PropTypes.oneOf(["line","circle"]),showInfo:d.PropTypes.bool,percent:d.PropTypes.number,width:d.PropTypes.number,strokeWidth:d.PropTypes.number,trailColor:d.PropTypes.string,format:d.PropTypes.func},p);t["default"]=C,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l=n(1),u=r(l),c=n(439),p=r(c),f=n(22),d=r(f),h=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.componentDidMount=function(){(0,d["default"])(!1,"`QueueAnim` is deprecated, you can import QueueAnim from 'rc-queue-anim' directly.The Demo will be moved to http://motion.ant.design/component/queue-anim")},t.prototype.render=function(){return u["default"].createElement(p["default"],this.props)},t}(u["default"].Component);t["default"]=h,e.exports=t["default"]},249,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}function u(e){var t=null,n=!1;return h["default"].Children.forEach(e,function(e){e&&e.props&&e.props.checked&&(t=e.props.value,n=!0)}),n?{value:t}:void 0}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=n(60),g=r(m),b=n(107),P=r(b),C=n(21),T=r(C),O=(p=c=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));r.onRadioChange=function(e){"value"in r.props||r.setState({value:e.target.value}),r.props.onChange(e)};var o=void 0;if("value"in n)o=n.value;else if("defaultValue"in n)o=n.defaultValue;else{var i=u(n.children);o=i&&i.value}return r.state={value:o},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){if("value"in e)this.setState({value:e.value});else{var t=u(e.children);t&&this.setState({value:t.value})}},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return T["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=this,n=this.props,r=h["default"].Children.map(n.children,function(e){if(e&&(e.type===g["default"]||e.type===P["default"])&&e.props){var n={};return"key"in e||"string"!=typeof e.props.value||(n.key=e.props.value),h["default"].cloneElement(e,f({},n,e.props,{onChange:t.onRadioChange,checked:t.state.value===e.props.value,disabled:e.props.disabled||t.props.disabled}))}return e}),o=(0,v["default"])((e={},i(e,n.prefixCls,!0),i(e,n.prefixCls+"-"+n.size,n.size),e));return h["default"].createElement("div",{className:o,style:n.style},r)},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-radio-group",disabled:!1,onChange:function(){}},p);t["default"]=O,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(445),d=r(f),h=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(d["default"],this.props)},t}(p["default"].Component),l.propTypes={prefixCls:c.PropTypes.string},l.defaultProps={prefixCls:"ant-rate"},u);t["default"]=h,e.exports=t["default"]},[557,541],225,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(458),h=r(d),y=(c=u=function(e){function t(){return a(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.isIncluded,n=e.marks,r=e.index,o=e.defaultIndex,a=i(e,["isIncluded","marks","index","defaultIndex"]);return void 0!==t&&(a.included=t),Array.isArray(n)?(a.min=0,a.max=n.length-1,a.step=1,void 0!==r&&(a.value=r),void 0!==o&&(a.defaultValue=o),a.marks={},n.forEach(function(e,t){a.marks[t]=e})):a.marks=n,f["default"].createElement(h["default"],a)},t}(f["default"].Component),u.defaultProps={prefixCls:"ant-slider",tipTransitionName:"zoom-down"},c);t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(543),n(114)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(461),d=r(f),h=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(d["default"],this.props)},t}(p["default"].Component),l.Step=d["default"].Step,l.defaultProps={prefixCls:"ant-steps",iconPrefix:"ant",current:0},u);t["default"]=h,e.exports=t["default"]},[557,545],function(e,t,n){"use strict";n(3)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(463),d=r(f),h=n(1),y=r(h),v=n(2),m=r(v),g=(c=u=function(e){function t(){return a(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.size,o=t.className,a=(0,m["default"])((e={},i(e,o,!!o),i(e,n+"-small","small"===r),e));return y["default"].createElement(d["default"],p({className:a},this.props))},t}(y["default"].Component),u.defaultProps={prefixCls:"ant-switch"},c);t["default"]=g,e.exports=t["default"]},[557,546],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function c(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):o(e,t))}function p(){}function f(e){e.stopPropagation(),e.nativeEvent.stopImmediatePropagation&&e.nativeEvent.stopImmediatePropagation()}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var d,h,y,v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},m=n(1),g=r(m),b=n(467),P=r(b),C=n(34),T=r(C),O=n(43),w=r(O),x=n(280),E=r(x),S=n(102),k=r(S),N=n(6),j=r(N),_=n(109),M=r(_),D=n(2),A=r(D),L=n(283),V={filterTitle:"\u7b5b\u9009",filterConfirm:"\u786e\u5b9a",filterReset:"\u91cd\u7f6e",emptyText:g["default"].createElement("span",null,g["default"].createElement(j["default"],{type:"frown"}),"\u6682\u65e0\u6570\u636e")},I={onChange:p,onShowSizeChange:p},F=(h=d=function(e){function t(n){l(this,t);var r=u(this,e.call(this,n));y.call(r);var o=n.pagination||{};return r.state=v({selectedRowKeys:(n.rowSelection||{}).selectedRowKeys||[],filters:r.getFiltersFromColumns(),selectionDirty:!1},r.getSortStateFromColumns(),{pagination:r.hasPagination()?v({},I,o,{current:o.defaultCurrent||o.current||1,pageSize:o.defaultPageSize||o.pageSize||10}):{}}),r.CheckboxPropsCache={},r}return c(t,e),t.prototype.getCheckboxPropsByItem=function(e){var t=this.props.rowSelection,n=void 0===t?{}:t;if(!n.getCheckboxProps)return{};var r=this.getRecordKey(e);return this.CheckboxPropsCache[r]||(this.CheckboxPropsCache[r]=n.getCheckboxProps(e)),this.CheckboxPropsCache[r]},t.prototype.getDefaultSelection=function(){var e=this,t=this.props.rowSelection,n=void 0===t?{}:t;return n.getCheckboxProps?this.getFlatData().filter(function(t){return e.getCheckboxPropsByItem(t).defaultChecked}).map(function(t,n){return e.getRecordKey(t,n)}):[]},t.prototype.getLocale=function(){var e={};return this.context.antLocale&&this.context.antLocale.Table&&(e=this.context.antLocale.Table),v({},V,e,this.props.locale)},t.prototype.componentWillReceiveProps=function(e){var t=this;if("pagination"in e&&e.pagination!==!1&&this.setState(function(t){var n=v({},I,t.pagination,e.pagination);return n.current=n.current||1,{pagination:n}}),"dataSource"in e&&e.dataSource!==this.props.dataSource&&(this.setState({selectionDirty:!1}),this.CheckboxPropsCache={}),e.rowSelection&&"selectedRowKeys"in e.rowSelection){this.setState({selectedRowKeys:e.rowSelection.selectedRowKeys||[]});var n=this.props.rowSelection;n&&e.rowSelection.getCheckboxProps!==n.getCheckboxProps&&(this.CheckboxPropsCache={})}if(this.getSortOrderColumns(e.columns).length>0){var r=this.getSortStateFromColumns(e.columns);r.sortColumn===this.state.sortColumn&&r.sortOrder===this.state.sortOrder||this.setState(r)}var o=this.getFilteredValueColumns(e.columns);o.length>0&&!function(){var n=t.getFiltersFromColumns(e.columns),r=v({},t.state.filters);Object.keys(n).forEach(function(e){r[e]=n[e]}),t.isFiltersChanged(r)&&t.setState({filters:r})}()},t.prototype.setSelectedRowKeys=function(e,t){var n=this,r=t.selectWay,o=t.record,i=t.checked,a=t.changeRowKeys,s=this.props.rowSelection,l=void 0===s?{}:s;!l||"selectedRowKeys"in l||this.setState({selectedRowKeys:e});var u=this.getFlatData();if(l.onChange||l[r]){var c=u.filter(function(t,r){return e.indexOf(n.getRecordKey(t,r))>=0});if(l.onChange&&l.onChange(e,c),"onSelect"===r&&l.onSelect)l.onSelect(o,i,c);else if("onSelectAll"===r&&l.onSelectAll){var p=u.filter(function(e,t){return a.indexOf(n.getRecordKey(e,t))>=0});l.onSelectAll(i,c,p)}}},t.prototype.hasPagination=function(){return this.props.pagination!==!1},t.prototype.isFiltersChanged=function(e){var t=this,n=!1;return Object.keys(e).length!==Object.keys(this.state.filters).length?n=!0:Object.keys(e).forEach(function(r){e[r]!==t.state.filters[r]&&(n=!0)}),n},t.prototype.getSortOrderColumns=function(e){return(e||this.props.columns||[]).filter(function(e){return"sortOrder"in e})},t.prototype.getFilteredValueColumns=function(e){return(e||this.props.columns||[]).filter(function(e){return"filteredValue"in e})},t.prototype.getFiltersFromColumns=function(e){var t=this,n={};return this.getFilteredValueColumns(e).forEach(function(e){n[t.getColumnKey(e)]=e.filteredValue}),n},t.prototype.getSortStateFromColumns=function(e){var t=this.getSortOrderColumns(e).filter(function(e){return e.sortOrder})[0];return t?{sortColumn:t,sortOrder:t.sortOrder}:{sortColumn:null,sortOrder:null}},t.prototype.getSorterFn=function(){var e=this.state,t=e.sortOrder,n=e.sortColumn;if(t&&n&&"function"==typeof n.sorter)return function(e,r){var o=n.sorter(e,r);return 0!==o?"descend"===t?-o:o:0}},t.prototype.toggleSortOrder=function(e,t){var n,r=this.state,o=r.sortColumn,i=r.sortOrder,a=this.isSortColumn(t);a?i===e?(i="",o=null):i=e:(i=e,o=t);var l={sortOrder:i,sortColumn:o};0===this.getSortOrderColumns().length&&this.setState(l),(n=this.props).onChange.apply(n,s(this.prepareParamsArguments(v({},this.state,l))))},t.prototype.getRecordKey=function(e,t){var n=this.props.rowKey;return"function"==typeof n?n(e,t):e[n]||t},t.prototype.renderRowSelection=function(){var e=this,t=this.props.columns.concat();if(this.props.rowSelection){var n=this.getFlatCurrentPageData().filter(function(t){return!e.props.rowSelection.getCheckboxProps||!e.getCheckboxPropsByItem(t).disabled}),r=void 0;r=!!n.length&&(this.state.selectionDirty?n.every(function(t,n){return e.state.selectedRowKeys.indexOf(e.getRecordKey(t,n))>=0}):n.every(function(t,n){return e.state.selectedRowKeys.indexOf(e.getRecordKey(t,n))>=0})||n.every(function(t){return e.getCheckboxPropsByItem(t).defaultChecked}));var o=void 0;if("radio"===this.props.rowSelection.type)o={key:"selection-column",render:this.renderSelectionRadio,className:"ant-table-selection-column"};else{var i=n.every(function(t){return e.getCheckboxPropsByItem(t).disabled}),a=g["default"].createElement(T["default"],{checked:r,disabled:i,onChange:this.handleSelectAllRow});o={key:"selection-column",title:a,render:this.renderSelectionCheckBox,className:"ant-table-selection-column"}}t.some(function(e){return"left"===e.fixed||e.fixed===!0})&&(o.fixed="left"),t[0]&&"selection-column"===t[0].key?t[0]=o:t.unshift(o)}return t},t.prototype.getColumnKey=function(e,t){return e.key||e.dataIndex||t},t.prototype.getMaxCurrent=function(e){var t=this.state.pagination,n=t.current,r=t.pageSize;return(n-1)*r>=e?n-1:n},t.prototype.isSortColumn=function(e){var t=this.state.sortColumn;return!(!e||!t)&&this.getColumnKey(t)===this.getColumnKey(e)},t.prototype.renderColumnsDropdown=function(e){var t=this,n=this.state.sortOrder,r=this.getLocale();return e.map(function(e,o){var i=v({},e),a=t.getColumnKey(i,o),s=void 0,l=void 0;if(i.filters&&i.filters.length>0||i.filterDropdown){var u=t.state.filters[a]||[];s=g["default"].createElement(E["default"],{locale:r,column:i,selectedKeys:u,confirmFilter:t.handleFilter})}if(i.sorter){var c=t.isSortColumn(i);c&&(i.className=i.className||"",n&&(i.className+=" ant-table-column-sort"));var p=c&&"ascend"===n,f=c&&"descend"===n;l=g["default"].createElement("div",{className:"ant-table-column-sorter"},g["default"].createElement("span",{className:"ant-table-column-sorter-up "+(p?"on":"off"),title:"\u2191",onClick:function(){return t.toggleSortOrder("ascend",i)}},g["default"].createElement(j["default"],{type:"caret-up"})),g["default"].createElement("span",{className:"ant-table-column-sorter-down "+(f?"on":"off"),title:"\u2193",onClick:function(){return t.toggleSortOrder("descend",i)}},g["default"].createElement(j["default"],{type:"caret-down"})))}return i.title=g["default"].createElement("span",null,i.title,l,s),i})},t.prototype.renderPagination=function(){if(!this.hasPagination())return null;var e="default",t=this.state.pagination;t.size?e=t.size:"middle"!==this.props.size&&"small"!==this.props.size||(e="small");var n=t.total||this.getLocalData().length;return n>0?g["default"].createElement(k["default"],v({},t,{className:this.props.prefixCls+"-pagination",onChange:this.handlePageChange,total:n,size:e,current:this.getMaxCurrent(n),onShowSizeChange:this.handleShowSizeChange})):null},t.prototype.prepareParamsArguments=function(e){var t=e.pagination,n=e.filters,r={};return e.sortColumn&&e.sortOrder&&(r.column=e.sortColumn,r.order=e.sortOrder,r.field=e.sortColumn.dataIndex,r.columnKey=this.getColumnKey(e.sortColumn)),[t,n,r]},t.prototype.findColumn=function(e){var t=this;return this.props.columns.filter(function(n){return t.getColumnKey(n)===e})[0]},t.prototype.getCurrentPageData=function(){var e=this.getLocalData(),t=void 0,n=void 0,r=this.state;return this.hasPagination()?(n=r.pagination.pageSize,t=this.getMaxCurrent(r.pagination.total||e.length)):(n=Number.MAX_VALUE,t=1),(e.length>n||n===Number.MAX_VALUE)&&(e=e.filter(function(e,r){return r>=(t-1)*n&&r<t*n})),e},t.prototype.getFlatData=function(){return(0,L.flatArray)(this.getLocalData())},t.prototype.getFlatCurrentPageData=function(){return(0,L.flatArray)(this.getCurrentPageData())},t.prototype.recursiveSort=function(e,t){var n=this,r=this.props.childrenColumnName;return e.sort(t).map(function(e){return e[r]?v({},e,a({},r,n.recursiveSort(e[r],t))):e})},t.prototype.getLocalData=function(){var e=this,t=this.state,n=this.props.dataSource,r=n||[];r=r.slice(0);var o=this.getSorterFn();return o&&(r=this.recursiveSort(r,o)),t.filters&&Object.keys(t.filters).forEach(function(n){var o=e.findColumn(n);if(o){var i=t.filters[n]||[];0!==i.length&&(r=o.onFilter?r.filter(function(e){return i.some(function(t){return o.onFilter(t,e)})}):r)}}),r},t.prototype.render=function(){var e,t=this,n=this.props,r=n.style,o=n.className,s=i(n,["style","className"]),l=this.getCurrentPageData(),u=this.renderRowSelection(),c=this.props.expandedRowRender&&this.props.expandIconAsCell!==!1,p=this.getLocale(),f=(0,A["default"])((e={},a(e,"ant-table-"+this.props.size,!0),a(e,"ant-table-bordered",this.props.bordered),a(e,"ant-table-empty",!l.length),e));u=this.renderColumnsDropdown(u),u=u.map(function(e,n){var r=v({},e);return r.key=t.getColumnKey(r,n),r});var d=g["default"].createElement(P["default"],v({},s,{data:l,columns:u,className:f,expandIconColumnIndex:u[0]&&"selection-column"===u[0].key?1:0,expandIconAsCell:c,emptyText:function(){return p.emptyText}})),h=this.hasPagination()&&l&&0!==l.length?"ant-table-with-pagination":"ant-table-without-pagination",y=this.props.loading?h+" ant-table-spin-holder":"";return d=g["default"].createElement(M["default"],{className:y,spinning:this.props.loading},d),g["default"].createElement("div",{className:o+" clearfix",style:r},d,this.renderPagination())},t}(g["default"].Component),d.propTypes={dataSource:g["default"].PropTypes.array,prefixCls:g["default"].PropTypes.string,useFixedHeader:g["default"].PropTypes.bool,rowSelection:g["default"].PropTypes.object,className:g["default"].PropTypes.string,size:g["default"].PropTypes.string,loading:g["default"].PropTypes.bool,bordered:g["default"].PropTypes.bool,onChange:g["default"].PropTypes.func,locale:g["default"].PropTypes.object},d.defaultProps={dataSource:[],prefixCls:"ant-table",useFixedHeader:!1,rowSelection:null,className:"",size:"large",loading:!1,bordered:!1,indentSize:20,onChange:p,locale:{},rowKey:"key",childrenColumnName:"children"},d.contextTypes={antLocale:g["default"].PropTypes.object},y=function(){var e=this;this.handleFilter=function(t,n){var r=e.props,o=v({},e.state.pagination),i=v({},e.state.filters,a({},e.getColumnKey(t),n)),l=r.columns.map(function(t){return e.getColumnKey(t)});Object.keys(i).forEach(function(e){l.indexOf(e)<0&&delete i[e]}),r.pagination&&(o.current=1,o.onChange(o.current));var u={selectionDirty:!1,pagination:o},c=v({},i);e.getFilteredValueColumns().forEach(function(t){var n=e.getColumnKey(t);n&&delete c[n]}),Object.keys(c).length>0&&(u.filters=c),r.pagination&&"current"in r.pagination&&(u.pagination=v({},o,{current:e.state.pagination.current})),e.setState(u,function(){r.onChange.apply(r,s(e.prepareParamsArguments(v({},e.state,{selectionDirty:!1,filters:i,pagination:o}))))})},this.handleSelect=function(t,n,r){var o=r.target.checked,i=e.state.selectionDirty?[]:e.getDefaultSelection(),a=e.state.selectedRowKeys.concat(i),s=e.getRecordKey(t,n);o?a.push(e.getRecordKey(t,n)):a=a.filter(function(e){return s!==e}),e.setState({selectionDirty:!0}),e.setSelectedRowKeys(a,{selectWay:"onSelect",record:t,checked:o})},this.handleRadioSelect=function(t,n,r){var o=r.target.checked,i=e.state.selectionDirty?[]:e.getDefaultSelection(),a=e.state.selectedRowKeys.concat(i),s=e.getRecordKey(t,n);a=[s],e.setState({selectionDirty:!0}),e.setSelectedRowKeys(a,{selectWay:"onSelect",record:t,checked:o})},this.handleSelectAllRow=function(t){var n=t.target.checked,r=e.getFlatCurrentPageData(),o=e.state.selectionDirty?[]:e.getDefaultSelection(),i=e.state.selectedRowKeys.concat(o),a=r.filter(function(t){return!e.getCheckboxPropsByItem(t).disabled}).map(function(t,n){return e.getRecordKey(t,n)}),s=[];n?a.forEach(function(e){i.indexOf(e)<0&&(i.push(e),s.push(e))}):a.forEach(function(e){i.indexOf(e)>=0&&(i.splice(i.indexOf(e),1),s.push(e))}),e.setState({selectionDirty:!0}),e.setSelectedRowKeys(i,{selectWay:"onSelectAll",checked:n,changeRowKeys:s})},this.handlePageChange=function(t){var n,r=e.props,o=v({},e.state.pagination);t?o.current=t:o.current=o.current||1,o.onChange(o.current);var i={selectionDirty:!1,pagination:o};r.pagination&&"current"in r.pagination&&(i.pagination=v({},o,{current:e.state.pagination.current})),e.setState(i),(n=e.props).onChange.apply(n,s(e.prepareParamsArguments(v({},e.state,{selectionDirty:!1,pagination:o}))))},this.renderSelectionRadio=function(t,n,r){var o=e.getRecordKey(n,r),i=e.getCheckboxPropsByItem(n),a=void 0;return a=e.state.selectionDirty?e.state.selectedRowKeys.indexOf(o)>=0:e.state.selectedRowKeys.indexOf(o)>=0||e.getDefaultSelection().indexOf(o)>=0,g["default"].createElement("span",{onClick:f},g["default"].createElement(w["default"],{disabled:i.disabled,onChange:function(t){return e.handleRadioSelect(n,o,t)},value:o,checked:a}))},this.renderSelectionCheckBox=function(t,n,r){var o=e.getRecordKey(n,r),i=void 0;i=e.state.selectionDirty?e.state.selectedRowKeys.indexOf(o)>=0:e.state.selectedRowKeys.indexOf(o)>=0||e.getDefaultSelection().indexOf(o)>=0;var a=e.getCheckboxPropsByItem(n);return g["default"].createElement("span",{onClick:f},g["default"].createElement(T["default"],{checked:i,disabled:a.disabled,onChange:function(t){return e.handleSelect(n,o,t)}}))},this.handleShowSizeChange=function(t,n){var r,o=e.state.pagination;o.onShowSizeChange(t,n);var i=v({},o,{pageSize:n,current:t});e.setState({pagination:i}),(r=e.props).onChange.apply(r,s(e.prepareParamsArguments(v({},e.state,{pagination:i}))))}},h);t["default"]=F,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},p=n(1),f=r(p),d=n(40),h=r(d),y=n(95),v=r(y),m=n(6),g=r(m),b=n(34),P=r(b),C=n(43),T=r(C),O=function(e){var t=e.onClick,n=e.children;return f["default"].createElement("div",{className:"ant-table-filter-dropdown",onClick:t},n)},w=(u=l=function(e){function t(n){i(this,t);var r=a(this,e.call(this,n));return r.setSelectedKeys=function(e){var t=e.selectedKeys;r.setState({selectedKeys:t})},r.handleClearFilters=function(){r.setState({selectedKeys:[]},r.handleConfirm)},r.handleConfirm=function(){r.setState({visible:!1}),r.confirmFilter()},r.onVisibleChange=function(e){r.setState({visible:e}),e||r.confirmFilter()},r.handleMenuItemClick=function(e){if(!(e.keyPath.length<=1)){var t=r.state.keyPathOfSelectedItem;r.state.selectedKeys.indexOf(e.key)>=0?delete t[e.key]:t[e.key]=e.keyPath,r.setState({keyPathOfSelectedItem:t})}},r.state={selectedKeys:n.selectedKeys,keyPathOfSelectedItem:{},visible:!1},r}return s(t,e),t.prototype.componentWillReceiveProps=function(e){this.setState({selectedKeys:e.selectedKeys })},t.prototype.confirmFilter=function(){this.state.selectedKeys!==this.props.selectedKeys&&this.props.confirmFilter(this.props.column,this.state.selectedKeys)},t.prototype.renderMenuItem=function(e){var t=this.props.column,n=!("filterMultiple"in t)||t.filterMultiple;return f["default"].createElement(d.Item,{key:e.value},n?f["default"].createElement(P["default"],{checked:this.state.selectedKeys.indexOf(e.value.toString())>=0}):f["default"].createElement(T["default"],{checked:this.state.selectedKeys.indexOf(e.value.toString())>=0}),f["default"].createElement("span",null,e.text))},t.prototype.renderMenus=function(e){var t=this;return e.map(function(e){if(e.children&&e.children.length>0){var n=function(){var n=t.state.keyPathOfSelectedItem,r=Object.keys(n).some(function(t){return n[t].indexOf(e.value)>=0}),o=r?"ant-dropdown-submenu-contain-selected":"";return{v:f["default"].createElement(d.SubMenu,{title:e.text,className:o,key:e.value.toString()},e.children.map(function(e){return t.renderMenuItem(e)}))}}();if("object"===("undefined"==typeof n?"undefined":c(n)))return n.v}return t.renderMenuItem(e)})},t.prototype.render=function(){var e=this.props,t=e.column,n=e.locale,r=!("filterMultiple"in t)||t.filterMultiple,o=t.filterDropdown?t.filterDropdown:f["default"].createElement(O,null,f["default"].createElement(h["default"],{multiple:r,onClick:this.handleMenuItemClick,prefixCls:"ant-dropdown-menu",onSelect:this.setSelectedKeys,onDeselect:this.setSelectedKeys,selectedKeys:this.state.selectedKeys},this.renderMenus(t.filters)),f["default"].createElement("div",{className:"ant-table-filter-dropdown-btns"},f["default"].createElement("a",{className:"ant-table-filter-dropdown-link confirm",onClick:this.handleConfirm},n.filterConfirm),f["default"].createElement("a",{className:"ant-table-filter-dropdown-link clear",onClick:this.handleClearFilters},n.filterReset))),i=this.props.selectedKeys.length>0?"ant-table-filter-selected":"";return f["default"].createElement(v["default"],{trigger:["click"],overlay:o,visible:this.state.visible,onVisibleChange:this.onVisibleChange},f["default"].createElement(g["default"],{title:n.filterTitle,type:"filter",className:i}))},t}(f["default"].Component),l.defaultProps={handleFilter:function(){},column:null},u);t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(279),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(547),n(61),n(35),n(96),n(110),n(103)},function(e,t){"use strict";function n(){var e=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],t=arguments.length<=1||void 0===arguments[1]?"children":arguments[1],n=[],o=function i(e){e.forEach(function(e){var o=r({},e);delete o[t],n.push(o),e[t]&&e[t].length>0&&i(e[t])})};return o(e),n}Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.flatArray=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(473),d=r(f),h=n(1),y=r(h),v=n(2),m=r(v),g=n(6),b=r(g),P=(c=u=function(e){function t(){var n,r,o;a(this,t);for(var i=arguments.length,l=Array(i),u=0;u<i;u++)l[u]=arguments[u];return n=r=s(this,e.call.apply(e,[this].concat(l))),r.createNewTab=function(e){r.props.onEdit(e,"add")},r.removeTab=function(e,t){t.stopPropagation(),e&&r.props.onEdit(e,"remove")},r.handleChange=function(e){r.props.onChange(e)},o=n,s(r,o)}return l(t,e),t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.size,a=n.tabPosition,s=n.animation,l=n.type,u=n.children,c=n.tabBarExtraContent,f=n.hideAdd,v=(0,m["default"])((e={},i(e,this.props.className,!!this.props.className),i(e,r+"-mini","small"===o||"mini"===o),i(e,r+"-vertical","left"===a||"right"===a),i(e,r+"-card",l.indexOf("card")>=0),i(e,r+"-"+l,!0),e));("left"===a||"right"===a||l.indexOf("card")>=0)&&(s=null);var g=void 0;return"editable-card"===l&&(g=[],y["default"].Children.forEach(u,function(e,n){g.push((0,h.cloneElement)(e,{tab:y["default"].createElement("div",null,e.props.tab,y["default"].createElement(b["default"],{type:"cross",onClick:function(n){return t.removeTab(e.key,n)}})),key:e.key||n}))}),f||(c=y["default"].createElement("span",null,y["default"].createElement(b["default"],{type:"plus",className:r+"-new-tab",onClick:this.createNewTab}),c))),c=c?y["default"].createElement("div",{className:r+"-extra-content"},c):null,y["default"].createElement(d["default"],p({},this.props,{className:v,tabBarExtraContent:c,onChange:this.handleChange,animation:s}),g||u)},t}(y["default"].Component),u.TabPane=d["default"].TabPane,u.defaultProps={prefixCls:"ant-tabs",animation:"slide-horizontal",type:"line",onChange:function(){},onEdit:function(){},hideAdd:!1},c);t["default"]=P,e.exports=t["default"]},[557,548],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(4),v=r(y),m=n(9),g=r(m),b=n(6),P=r(b),C=n(2),T=r(C),O=n(27),w=r(O),x=(p=c=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));return r.close=function(e){if(r.props.onClose(e),!e.defaultPrevented){var t=v["default"].findDOMNode(r);t.style.width=t.getBoundingClientRect().width+"px",t.style.width=t.getBoundingClientRect().width+"px",r.setState({closing:!0})}},r.animationEnd=function(e,t){t||r.state.closed||(r.setState({closed:!0,closing:!1}),r.props.afterClose())},r.state={closing:!1,closed:!1},r}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.closable,o=t.color,s=t.className,l=t.children,u=a(t,["prefixCls","closable","color","className","children"]),c=r?h["default"].createElement(P["default"],{type:"cross",onClick:this.close}):"",p=(0,T["default"])((e={},i(e,n,!0),i(e,n+"-"+o,!!o),i(e,n+"-close",this.state.closing),i(e,s,!!s),e)),d=(0,w["default"])(u,["onClose","afterClose"]);return h["default"].createElement(g["default"],{component:"",showProp:"data-show",transitionName:n+"-zoom",transitionAppear:!0,onEnd:this.animationEnd},this.state.closed?null:h["default"].createElement("div",f({"data-show":!this.state.closing},d,{className:p,style:{backgroundColor:/blue|red|green|yellow/.test(o)?null:o}}),h["default"].createElement("span",{className:n+"-text"},l),c))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-tag",closable:!1,onClose:function(){},afterClose:function(){}},p);t["default"]=x,e.exports=t["default"]},[557,549],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(53),y=r(h),v=n(160),m=r(v),g=n(111),b=r(g),P=n(2),C=r(P),T=n(14),O=r(T),w=(c=u=function(e){function t(){var n,r,o;a(this,t);for(var i=arguments.length,l=Array(i),u=0;u<i;u++)l[u]=arguments[u];return n=r=s(this,e.call.apply(e,[this].concat(l))),r.handleChange=function(e){r.props.onChange(e?new Date(e.getTime()):null,e?r.getFormatter().format(e):"")},o=n,s(r,o)}return l(t,e),t.prototype.getFormatter=function(){return new y["default"](this.props.format,this.getLocale().format)},t.prototype.getSizeClass=function(){var e="";return"large"===this.props.size?e=" ant-input-lg":"small"===this.props.size&&(e=" ant-input-sm"),e},t.prototype.parseTimeFromValue=function(e){if(e){if("string"==typeof e)return this.getFormatter().parse(e,{locale:this.getLocale().calendar,obeyCount:!0});if(e instanceof Date){var t=new O["default"](this.getLocale().calendar);return t.setTime(+e),t}}return e},t.prototype.getLocale=function(){var e=b["default"];return this.context.antLocale&&this.context.antLocale.TimePicker&&(e=this.context.antLocale.TimePicker),p({},e,this.props.locale)},t.prototype.render=function(){var e,t=this.getLocale(),n=p({},this.props);n.placeholder="placeholder"in this.props?n.placeholder:t.placeholder,n.defaultValue?n.defaultValue=this.parseTimeFromValue(n.defaultValue):delete n.defaultValue,n.value&&(n.value=this.parseTimeFromValue(n.value));var r=(0,C["default"])((e={},i(e,n.className,!!n.className),i(e,n.prefixCls+"-"+n.size,!!n.size),e));return n.format.indexOf("ss")<0&&(n.showSecond=!1),n.format.indexOf("HH")<0&&(n.showHour=!1),d["default"].createElement(m["default"],p({},n,{className:r,locale:t,formatter:this.getFormatter(),onChange:this.handleChange}))},t}(d["default"].Component),u.defaultProps={format:"HH:mm:ss",prefixCls:"ant-time-picker",onChange:function(){},locale:{},align:{offset:[0,-2]},disabled:!1,disabledHours:void 0,disabledMinutes:void 0,disabledSeconds:void 0,hideDisabledOptions:!1,placement:"bottomLeft",transitionName:"slide-up"},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=n(113),g=r(m),b=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.children,o=t.pending,s=t.className,l=a(t,["prefixCls","children","pending","className"]),u="boolean"==typeof o?null:o,c=(0,v["default"])((e={},i(e,n,!0),i(e,n+"-pending",!!o),i(e,s,s),e));return h["default"].createElement("ul",f({},l,{className:c}),h["default"].Children.map(r,function(e,t){return h["default"].cloneElement(e,{last:t===r.length-1})}),o?h["default"].createElement(g["default"],{pending:!!o},u):null)},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-timeline"},p);t["default"]=b,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(289),i=r(o),a=n(113),s=r(a);i["default"].Item=s["default"],t["default"]=i["default"],e.exports=t["default"]},[557,551],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function c(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var p,f,d=n(1),h=r(d),y=n(293),v=r(y),m=n(294),g=r(m),b=n(115),P=r(b),C=n(2),T=r(C),O=(f=p=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));return r.moveTo=function(e){var t=r.props.targetKeys,n=r.state,o=n.leftCheckedKeys,i=n.rightCheckedKeys,s="right"===e?o:i,l="right"===e?s.concat(t):t.filter(function(e){return!s.some(function(t){return e===t})});r.setState(a({},"right"===e?"leftCheckedKeys":"rightCheckedKeys",[])),r.props.onChange(l,e,s)},r.moveToLeft=function(){return r.moveTo("left")},r.moveToRight=function(){return r.moveTo("right")},r.handleSelectAll=function(e,t,n){var o=n?[]:t.map(function(e){return e.key});r.setState(a({},e+"CheckedKeys",o))},r.handleLeftSelectAll=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return r.handleSelectAll.apply(r,["left"].concat(t))},r.handleRightSelectAll=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return r.handleSelectAll.apply(r,["right"].concat(t))},r.handleFilter=function(e,t){r.setState(a({},e+"Filter",t.target.value))},r.handleLeftFilter=function(e){return r.handleFilter("left",e)},r.handleRightFilter=function(e){return r.handleFilter("right",e)},r.handleClear=function(e){r.setState(a({},e+"Filter",""))},r.handleLeftClear=function(){return r.handleClear("left")},r.handleRightClear=function(){return r.handleClear("right")},r.handleSelect=function(e,t,n){var o=r.state,s=o.leftCheckedKeys,l=o.rightCheckedKeys,u="left"===e?[].concat(i(s)):[].concat(i(l)),c=void 0;u.forEach(function(e,n){e===t.key&&(c=n)}),c>-1&&u.splice(c,1),n&&u.push(t.key),r.setState(a({},e+"CheckedKeys",u))},r.handleLeftSelect=function(e,t){return r.handleSelect("left",e,t)},r.handleRightSelect=function(e,t){return r.handleSelect("right",e,t)},r.state={leftFilter:"",rightFilter:"",leftCheckedKeys:[],rightCheckedKeys:[]},r}return u(t,e),t.prototype.componentWillReceiveProps=function(e){var t=this,n=this.state,r=n.leftCheckedKeys,o=n.rightCheckedKeys;e.targetKeys===this.props.targetKeys&&e.dataSource===this.props.dataSource||!function(){t.splitedDataSource=null;var n=e.dataSource,i=e.targetKeys;t.setState({leftCheckedKeys:r.filter(function(e){return n.filter(function(t){return t.key===e}).length}).filter(function(e){return 0===i.filter(function(t){return t===e}).length}),rightCheckedKeys:o.filter(function(e){return n.filter(function(t){return t.key===e}).length}).filter(function(e){return i.filter(function(t){return t===e}).length>0})})}()},t.prototype.splitDataSource=function(e){if(this.splitedDataSource)return this.splitedDataSource;var t=e.targetKeys,n=e.dataSource;e.rowKey&&(n=n.map(function(t){return t.key=e.rowKey(t),t}));var r=[].concat(i(n)),o=[];return t.length>0&&t.forEach(function(e){o.push(r.filter(function(t,n){return t.key===e&&(r.splice(n,1),!0)})[0])}),this.splitedDataSource={leftDataSource:r,rightDataSource:o},this.splitedDataSource},t.prototype.render=function n(){var e,t=this.props,r=t.prefixCls,o=t.titles,i=t.operations,s=t.showSearch,l=t.notFoundContent,u=t.searchPlaceholder,c=t.body,p=t.footer,f=t.listStyle,d=t.className,y=t.filterOption,n=t.render,m=this.state,b=m.leftFilter,P=m.rightFilter,C=m.leftCheckedKeys,O=m.rightCheckedKeys,w=this.splitDataSource(this.props),x=w.leftDataSource,E=w.rightDataSource,S=O.length>0,k=C.length>0,N=(0,T["default"])((e={},a(e,d,!!d),a(e,r,!0),e));return h["default"].createElement("div",{className:N},h["default"].createElement(v["default"],{titleText:o[0],dataSource:x,filter:b,filterOption:y,style:f,checkedKeys:C,handleFilter:this.handleLeftFilter,handleClear:this.handleLeftClear,handleSelect:this.handleLeftSelect,handleSelectAll:this.handleLeftSelectAll,render:n,showSearch:s,searchPlaceholder:u,notFoundContent:l,body:c,footer:p,prefixCls:r+"-list"}),h["default"].createElement(g["default"],{rightActive:k,rightArrowText:i[0],moveToRight:this.moveToRight,leftActive:S,leftArrowText:i[1],moveToLeft:this.moveToLeft,className:r+"-operation"}),h["default"].createElement(v["default"],{titleText:o[1],dataSource:E,filter:P,filterOption:y,style:f,checkedKeys:O,handleFilter:this.handleRightFilter,handleClear:this.handleRightClear,handleSelect:this.handleRightSelect,handleSelectAll:this.handleRightSelectAll,render:n,showSearch:s,searchPlaceholder:u,notFoundContent:l,body:c,footer:p,prefixCls:r+"-list"}))},t}(h["default"].Component),p.List=v["default"],p.Operation=g["default"],p.Search=P["default"],p.defaultProps={prefixCls:"ant-transfer",dataSource:[],render:c,targetKeys:[],onChange:c,titles:["\u6e90\u5217\u8868","\u76ee\u7684\u5217\u8868"],operations:[],showSearch:!1,body:c,footer:c},p.propTypes={prefixCls:d.PropTypes.string,dataSource:d.PropTypes.array,render:d.PropTypes.func,targetKeys:d.PropTypes.array,onChange:d.PropTypes.func,height:d.PropTypes.number,listStyle:d.PropTypes.object,className:d.PropTypes.string,titles:d.PropTypes.array,operations:d.PropTypes.array,showSearch:d.PropTypes.bool,filterOption:d.PropTypes.func,searchPlaceholder:d.PropTypes.string,notFoundContent:d.PropTypes.node,body:d.PropTypes.func,footer:d.PropTypes.func,rowKey:d.PropTypes.func},f);t["default"]=O,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}function u(){}function c(e){return e&&!y["default"].isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var p,f,d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.isRenderResultPlainObject=c;var h=n(1),y=r(h),v=n(34),m=r(v),g=n(115),b=r(g),P=n(2),C=r(P),T=n(9),O=r(T),w=n(21),x=r(w),E=(f=p=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return r.handleSelect=function(e){var t=r.props.checkedKeys,n=t.some(function(t){return t===e.key});r.props.handleSelect(e,!n)},r.handleFilter=function(e){r.props.handleFilter(e)},r.handleClear=function(){r.props.handleClear()},r.state={mounted:!1},r}return l(t,e),t.prototype.componentDidMount=function(){var e=this;this.timer=setTimeout(function(){e.setState({mounted:!0})},0)},t.prototype.componentWillUnmount=function(){clearTimeout(this.timer)},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return x["default"].shouldComponentUpdate.apply(this,t)},t.prototype.getCheckStatus=function(e){var t=this.props.checkedKeys;return 0===t.length?"none":e.every(function(e){return t.indexOf(e.key)>=0})?"all":"part"},t.prototype.renderCheckbox=function(e){var t,n=this,r=e.prefixCls,o=e.filteredDataSource,a=e.checked,s=e.checkPart,l=e.disabled,u=e.checkable,c=!s&&a,p=(0,C["default"])((t={},i(t,r+"-checkbox",!0),i(t,r+"-checkbox-indeterminate",s),i(t,r+"-checkbox-checked",c),i(t,r+"-checkbox-disabled",l),t));return y["default"].createElement("span",{ref:"checkbox",className:p,onClick:function(){return n.props.handleSelectAll(o,c)}},"boolean"!=typeof u?u:null)},t.prototype.matchFilter=function(e,t,n){var r=this.props.filterOption;return r?r(e,t):n.indexOf(e)>=0},t.prototype.render=function n(){var e,t=this,r=this.props,o=r.prefixCls,a=r.dataSource,s=r.titleText,l=r.filter,u=r.checkedKeys,p=r.body,f=r.footer,h=r.showSearch,n=r.render,v=r.style,g=this.props,P=g.searchPlaceholder,T=g.notFoundContent,w=f(d({},this.props)),x=p(d({},this.props)),E=(0,C["default"])((e={},i(e,o,!0),i(e,o+"-with-footer",!!w),e)),S=[],k=a.map(function(e){var r=n(e),o=void 0,i=void 0;return c(r)?(o=r.value,i=r.label):(o=r,i=r),l&&l.trim()&&!t.matchFilter(l,e,o)?null:(S.push(e),y["default"].createElement("li",{onClick:function(){return t.handleSelect(e)},key:e.key,title:o},y["default"].createElement(m["default"],{checked:u.some(function(t){return t===e.key})}),y["default"].createElement("span",null,i)))}).filter(function(e){return!!e}),N="\u6761";this.context.antLocale&&this.context.antLocale.Transfer&&(N=a.length>1?this.context.antLocale.Transfer.itemsUnit:this.context.antLocale.Transfer.itemUnit,P=P||this.context.antLocale.Transfer.searchPlaceholder,T=T||this.context.antLocale.Transfer.notFoundContent);var j=this.getCheckStatus(S);return y["default"].createElement("div",{className:E,style:v},y["default"].createElement("div",{className:o+"-header"},this.renderCheckbox({prefixCls:"ant-transfer",checked:"all"===j,checkPart:"part"===j,checkable:y["default"].createElement("span",{className:"ant-transfer-checkbox-inner"}),filteredDataSource:S}),y["default"].createElement("span",{className:o+"-header-selected"},y["default"].createElement("span",null,(u.length>0?u.length+"/":"")+a.length," ",N),y["default"].createElement("span",{className:o+"-header-title"},s))),x||y["default"].createElement("div",{className:h?o+"-body "+o+"-body-with-search":o+"-body"},h?y["default"].createElement("div",{className:o+"-body-search-wrapper"},y["default"].createElement(b["default"],{prefixCls:o+"-search",onChange:this.handleFilter,handleClear:this.handleClear,placeholder:P||"\u8bf7\u8f93\u5165\u641c\u7d22\u5185\u5bb9",value:l})):null,y["default"].createElement(O["default"],{component:"ul",transitionName:this.state.mounted?o+"-highlight":"",transitionLeave:!1},k.length>0?k:y["default"].createElement("div",{className:o+"-body-not-found"},T||"\u5217\u8868\u4e3a\u7a7a"))),w?y["default"].createElement("div",{className:o+"-footer"},w):null)},t}(y["default"].Component),p.defaultProps={dataSource:[],titleText:"",showSearch:!1,handleClear:u,handleFilter:u,handleSelect:u,handleSelectAll:u,render:u,body:u,footer:u},p.propTypes={prefixCls:h.PropTypes.string,dataSource:h.PropTypes.array,showSearch:h.PropTypes.bool,filterOption:h.PropTypes.func,searchPlaceholder:h.PropTypes.string,titleText:h.PropTypes.string,style:h.PropTypes.object,handleClear:h.PropTypes.func,handleFilter:h.PropTypes.func,handleSelect:h.PropTypes.func,handleSelectAll:h.PropTypes.func,render:h.PropTypes.func,body:h.PropTypes.func,footer:h.PropTypes.func},p.contextTypes={antLocale:y["default"].PropTypes.object},f);t["default"]=E},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(29),h=r(d),y=n(6),v=r(y),m=(c=u=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.moveToLeft,n=e.moveToRight,r=e.leftArrowText,o=e.rightArrowText,i=e.leftActive,a=e.rightActive,s=e.className,l=f["default"].createElement(h["default"],{type:"primary",size:"small",disabled:!i,onClick:t},f["default"].createElement("span",null,f["default"].createElement(v["default"],{type:"left"}),r)),u=f["default"].createElement(h["default"],{type:"primary",size:"small",disabled:!a,onClick:n},f["default"].createElement("span",null,o,f["default"].createElement(v["default"],{type:"right"})));return f["default"].createElement("div",{className:s},l,u)},t}(f["default"].Component),u.defaultProps={leftArrowText:"",rightArrowText:"",moveToLeft:l,moveToRight:l},u.propTypes={className:p.PropTypes.string,leftArrowText:p.PropTypes.string,rightArrowText:p.PropTypes.string,moveToLeft:p.PropTypes.func,moveToRight:p.PropTypes.func},c);t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(553),n(35),n(42),n(23)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(487),y=r(h),v=n(2),m=r(v),g=(c=u=function(e){function t(){return a(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=this.props,r=n.size,o=n.className,a=n.combobox,s=n.notFoundContent,l=n.prefixCls,u=(0,m["default"])((e={},i(e,l+"-lg","large"===r),i(e,l+"-sm","small"===r),i(e,o,!!o),e)),c=this.context.antLocale;c&&c.Select&&(s=s||c.Select.notFoundContent),a&&(s=null);var f=t.treeCheckable;return f&&(f=d["default"].createElement("span",{className:l+"-tree-checkbox-inner"})),d["default"].createElement(y["default"],p({},this.props,{treeCheckable:f,className:u,notFoundContent:s}))},t}(d["default"].Component),u.TreeNode=h.TreeNode,u.SHOW_ALL=h.SHOW_ALL,u.SHOW_PARENT=h.SHOW_PARENT,u.SHOW_CHILD=h.SHOW_CHILD,u.defaultProps={prefixCls:"ant-select",transitionName:"slide-up",choiceTransitionName:"zoom",showSearch:!1,dropdownClassName:"ant-select-tree-dropdown"},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(554),n(45),n(35)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]); }return e},p=n(1),f=r(p),d=n(166),h=r(d),y=n(89),v=r(y),m=(u=l=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.checkable;return t&&(t=f["default"].createElement("span",{className:e.prefixCls+"-checkbox-inner"})),f["default"].createElement(h["default"],c({},e,{checkable:t}),this.props.children)},t}(f["default"].Component),l.TreeNode=h["default"].TreeNode,l.defaultProps={prefixCls:"ant-tree",checkable:!1,showIcon:!1,openAnimation:v["default"]},u);t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(555),n(35)},function(e,t){"use strict";function n(e,t){var n=e.uid?"byUid":"byName",r=t.filter(function(t){return"byName"===n?t.name===e.name:t.uid===e.uid})[0];return r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}function u(){}function c(){return!0}function p(e){return{lastModified:e.lastModified,lastModifiedDate:e.lastModifiedDate,name:e.filename||e.name,size:e.size,type:e.type,uid:e.uid,response:e.response,error:e.error,percent:0,originFileObj:e}}function f(){var e=.1,t=.01,n=.98;return function(r){var o=r;return o>=n?o:(o+=e,e-=t,e<.001&&(e=.001),100*o)}}function d(e){return g["default"].createElement(k,v({},e,{type:"drag",style:{height:e.height}}))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var h,y,v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},m=n(1),g=r(m),b=n(497),P=r(b),C=n(303),T=r(C),O=n(300),w=r(O),x=n(2),E=r(x),S="ant-upload",k=(y=h=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return r.onStart=function(e){var t=void 0,n=r.state.fileList.concat();e.length>0?(t=e.map(function(e){var t=p(e);return t.status="uploading",t}),n=n.concat(t)):(t=p(e),t.status="uploading",n.push(t)),r.onChange({file:t,fileList:n}),window.FormData||r.autoUpdateProgress(0,t)},r.onSuccess=function(e,t){r.clearProgressTimer();try{"string"==typeof e&&(e=JSON.parse(e))}catch(n){}var o=r.state.fileList,i=(0,w["default"])(t,o);i&&(i.status="done",i.response=e,r.onChange({file:i,fileList:o}))},r.onProgress=function(e,t){var n=r.state.fileList,o=(0,w["default"])(t,n);o&&(o.percent=e.percent,r.onChange({event:e,file:o,fileList:r.state.fileList}))},r.onError=function(e,t,n){r.clearProgressTimer();var o=r.state.fileList,i=(0,w["default"])(n,o);i&&(i.error=e,i.response=t,i.status="error",r.handleRemove(i))},r.handleManualRemove=function(e){r.refs.upload.abort(e),e.status="removed","onRemove"in r.props?r.props.onRemove(e):r.handleRemove(e)},r.onChange=function(e){"fileList"in r.props||r.setState({fileList:e.fileList}),r.props.onChange(e)},r.onFileDrop=function(e){r.setState({dragState:e.type})},r.state={fileList:r.props.fileList||r.props.defaultFileList||[],dragState:"drop"},r}return l(t,e),t.prototype.autoUpdateProgress=function(e,t){var n=this,r=f(),o=0;this.progressTimer=setInterval(function(){o=r(o),n.onProgress({percent:o},t)},200)},t.prototype.removeFile=function(e){var t=this.state.fileList,n=(0,w["default"])(e,t),r=t.indexOf(n);return r!==-1?(t.splice(r,1),t):null},t.prototype.handleRemove=function(e){var t=this.removeFile(e);t&&this.onChange({file:e,fileList:t})},t.prototype.componentWillReceiveProps=function(e){"fileList"in e&&this.setState({fileList:e.fileList||[]})},t.prototype.clearProgressTimer=function(){clearInterval(this.progressTimer)},t.prototype.render=function(){var e,t=this.props.type||"select",n=v({},this.props,{onStart:this.onStart,onError:this.onError,onProgress:this.onProgress,onSuccess:this.onSuccess,beforeUpload:this.props.beforeUpload}),r=void 0;if(this.props.showUploadList&&(r=g["default"].createElement(T["default"],{listType:this.props.listType,items:this.state.fileList,onPreview:n.onPreview,onRemove:this.handleManualRemove})),"drag"===t){var o,a=(0,E["default"])((o={},i(o,S,!0),i(o,S+"-drag",!0),i(o,S+"-drag-uploading",this.state.fileList.some(function(e){return"uploading"===e.status})),i(o,S+"-drag-hover","dragover"===this.state.dragState),i(o,S+"-disabled",this.props.disabled),o));return g["default"].createElement("span",{className:this.props.className},g["default"].createElement("div",{className:a,onDrop:this.onFileDrop,onDragOver:this.onFileDrop,onDragLeave:this.onFileDrop},g["default"].createElement(P["default"],v({},n,{ref:"upload"}),g["default"].createElement("div",{className:S+"-drag-container"},this.props.children))),r)}var s=(0,E["default"])((e={},i(e,S,!0),i(e,S+"-select",!0),i(e,S+"-select-"+this.props.listType,!0),i(e,S+"-disabled",this.props.disabled),e)),l=this.props.children?g["default"].createElement("div",{className:s},g["default"].createElement(P["default"],v({},n,{ref:"upload"}))):null;return"picture-card"===this.props.listType?g["default"].createElement("span",{className:this.props.className},r,l):g["default"].createElement("span",{className:this.props.className},l,r)},t}(g["default"].Component),h.Dragger=d,h.defaultProps={type:"select",multiple:!1,action:"",data:{},accept:"",onChange:u,beforeUpload:c,showUploadList:!0,listType:"text",className:"",disabled:!1},y);t["default"]=k,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(556),n(106)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(9),y=r(h),v=n(6),m=r(v),g=n(105),b=r(g),P=n(2),C=r(P),T="ant-upload",O=function(e,t){var n=new FileReader;n.onloadend=function(){return t(n.result)},n.readAsDataURL(e)},w=(c=u=function(e){function t(){var n,r,o;a(this,t);for(var i=arguments.length,l=Array(i),u=0;u<i;u++)l[u]=arguments[u];return n=r=s(this,e.call.apply(e,[this].concat(l))),r.handleClose=function(e){r.props.onRemove(e)},r.handlePreview=function(e,t){if(r.props.onPreview)return t.preventDefault(),r.props.onPreview(e)},o=n,s(r,o)}return l(t,e),t.prototype.componentDidUpdate=function(){var e=this;"picture"!==this.props.listType&&"picture-card"!==this.props.listType||this.props.items.forEach(function(t){"undefined"!=typeof document&&"undefined"!=typeof window&&window.FileReader&&window.File&&t.originFileObj instanceof File&&void 0===t.thumbUrl&&(t.thumbUrl="",O(t.originFileObj,function(n){t.thumbUrl=n,e.forceUpdate()}))})},t.prototype.render=function(){var e,t=this,n=this.props.items.map(function(e){var n,r=void 0,o=d["default"].createElement(m["default"],{type:"paper-clip"});"picture"!==t.props.listType&&"picture-card"!==t.props.listType||(o="uploading"===e.status||!e.thumbUrl&&!e.url?"picture-card"===t.props.listType?d["default"].createElement("div",{className:T+"-list-item-uploading-text"},"\u6587\u4ef6\u4e0a\u4f20\u4e2d"):d["default"].createElement(m["default"],{className:T+"-list-item-thumbnail",type:"picture"}):d["default"].createElement("a",{className:T+"-list-item-thumbnail",onClick:function(n){return t.handlePreview(e,n)},href:e.url,target:"_blank"},d["default"].createElement("img",{src:e.thumbUrl||e.url,alt:e.name}))),"uploading"===e.status&&(r=d["default"].createElement("div",{className:T+"-list-item-progress"},d["default"].createElement(b["default"],p({type:"line"},t.props.progressAttr,{percent:e.percent}))));var a=(0,C["default"])((n={},i(n,T+"-list-item",!0),i(n,T+"-list-item-"+e.status,!0),n));return d["default"].createElement("div",{className:a,key:e.uid},d["default"].createElement("div",{className:T+"-list-item-info"},o,e.url?d["default"].createElement("a",{href:e.url,target:"_blank",className:T+"-list-item-name",onClick:function(n){return t.handlePreview(e,n)}},e.name):d["default"].createElement("span",{className:T+"-list-item-name",onClick:function(n){return t.handlePreview(e,n)}},e.name),"picture-card"===t.props.listType&&"uploading"!==e.status?d["default"].createElement("span",null,d["default"].createElement("a",{href:e.url,target:"_blank",style:{pointerEvents:e.url?"":"none"},onClick:function(n){return t.handlePreview(e,n)}},d["default"].createElement(m["default"],{type:"eye-o"})),d["default"].createElement(m["default"],{type:"delete",onClick:function(){return t.handleClose(e)}})):d["default"].createElement(m["default"],{type:"cross",onClick:function(){return t.handleClose(e)}})),r)}),r=(0,C["default"])((e={},i(e,T+"-list",!0),i(e,T+"-list-"+this.props.listType,!0),e));return d["default"].createElement("div",{className:r},d["default"].createElement(y["default"],{transitionName:T+"-margin-top"},n))},t}(d["default"].Component),u.defaultProps={listType:"text",items:[],progressAttr:{strokeWidth:3,showInfo:!1}},c);t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l=n(1),u=r(l),c=n(22),p=r(c),f=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.componentDidMount=function(){(0,p["default"])(!1,"`Validation` is removed, please use `Form` which has supported validation after antd@0.12.0, or you can just import Validation from 'rc-form-validation' for compatibility")},t.prototype.render=function(){return null},t}(u["default"].Component);t["default"]=f,f.Validator=function(){},f.FieldMixin={setField:function(){}},e.exports=t["default"]},249,function(e,t,n){"use strict";function r(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-(\w)/g,function(e,t){return t.toUpperCase()})}var o=n(175);o.keys().forEach(function(e){var n=o(e),i=e.match(/^\.\/([^_][\w-]+)\/index\.jsx?$/);i&&i[1]&&("message"===i[1]||"notification"===i[1]?t[i[1]]=n:t[r(i[1])]=n)})},function(e,t,n){e.exports={"default":n(316),__esModule:!0}},function(e,t,n){e.exports={"default":n(317),__esModule:!0}},function(e,t,n){e.exports={"default":n(318),__esModule:!0}},function(e,t,n){e.exports={"default":n(319),__esModule:!0}},function(e,t,n){e.exports={"default":n(321),__esModule:!0}},function(e,t,n){e.exports={"default":n(322),__esModule:!0}},function(e,t,n){e.exports={"default":n(323),__esModule:!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(307),i=r(o);t["default"]=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return(0,i["default"])(e)}},function(e,t){var n=!("undefined"==typeof window||!window.document||!window.document.createElement);e.exports=n},function(e,t,n){n(129),n(348),e.exports=n(11).Array.from},function(e,t,n){n(350),e.exports=n(11).Object.assign},function(e,t,n){n(351);var r=n(11).Object;e.exports=function(e,t){return r.create(e,t)}},function(e,t,n){n(352);var r=n(11).Object;e.exports=function(e,t,n){return r.defineProperty(e,t,n)}},function(e,t,n){n(353),e.exports=n(11).Object.keys},function(e,t,n){n(354),e.exports=n(11).Object.setPrototypeOf},function(e,t,n){n(356),n(355),n(357),n(358),e.exports=n(11).Symbol},function(e,t,n){n(129),n(359),e.exports=n(76).f("iterator")},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){e.exports=function(){}},function(e,t,n){var r=n(26),o=n(128),i=n(346);e.exports=function(e){return function(t,n,a){var s,l=r(t),u=o(l.length),c=i(a,u);if(e&&n!=n){for(;u>c;)if(s=l[c++],s!=s)return!0}else for(;u>c;c++)if((e||c in l)&&l[c]===n)return e||c||0;return!e&&-1}}},function(e,t,n){var r=n(63),o=n(13)("toStringTag"),i="Arguments"==r(function(){return arguments}()),a=function(e,t){try{return e[t]}catch(n){}};e.exports=function(e){var t,n,s;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=a(t=Object(e),o))?n:i?r(t):"Object"==(s=r(t))&&"function"==typeof t.callee?"Arguments":s}},function(e,t,n){"use strict";var r=n(18),o=n(38);e.exports=function(e,t,n){t in e?r.f(e,t,o(0,n)):e[t]=n}},function(e,t,n){var r=n(33),o=n(69),i=n(50);e.exports=function(e){var t=r(e),n=o.f;if(n)for(var a,s=n(e),l=i.f,u=0;s.length>u;)l.call(e,a=s[u++])&&t.push(a);return t}},function(e,t,n){e.exports=n(17).document&&document.documentElement},function(e,t,n){var r=n(37),o=n(13)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[o]===e)}},function(e,t,n){var r=n(63);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){var r=n(30);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(i){var a=e["return"];throw void 0!==a&&r(a.call(e)),i}}},function(e,t,n){"use strict";var r=n(68),o=n(38),i=n(70),a={};n(32)(a,n(13)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(a,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){var r=n(13)("iterator"),o=!1;try{var i=[7][r]();i["return"]=function(){o=!0},Array.from(i,function(){throw 2})}catch(a){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var i=[7],a=i[r]();a.next=function(){return{done:n=!0}},i[r]=function(){return a},e(i)}catch(s){}return n}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(33),o=n(26);e.exports=function(e,t){for(var n,i=o(e),a=r(i),s=a.length,l=0;s>l;)if(i[n=a[l++]]===t)return n}},function(e,t,n){var r=n(52)("meta"),o=n(36),i=n(25),a=n(18).f,s=0,l=Object.isExtensible||function(){return!0},u=!n(31)(function(){return l(Object.preventExtensions({}))}),c=function(e){a(e,r,{value:{i:"O"+ ++s,w:{}}})},p=function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!l(e))return"F";if(!t)return"E";c(e)}return e[r].i},f=function(e,t){if(!i(e,r)){if(!l(e))return!0;if(!t)return!1;c(e)}return e[r].w},d=function(e){return u&&h.NEED&&l(e)&&!i(e,r)&&c(e),e},h=e.exports={KEY:r,NEED:!1,fastKey:p,getWeak:f,onFreeze:d}},function(e,t,n){"use strict";var r=n(33),o=n(69),i=n(50),a=n(51),s=n(122),l=Object.assign;e.exports=!l||n(31)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=l({},e)[n]||Object.keys(l({},t)).join("")!=r})?function(e,t){for(var n=a(e),l=arguments.length,u=1,c=o.f,p=i.f;l>u;)for(var f,d=s(arguments[u++]),h=c?r(d).concat(c(d)):r(d),y=h.length,v=0;y>v;)p.call(d,f=h[v++])&&(n[f]=d[f]);return n}:l},function(e,t,n){var r=n(18),o=n(30),i=n(33);e.exports=n(24)?Object.defineProperties:function(e,t){o(e);for(var n,a=i(t),s=a.length,l=0;s>l;)r.f(e,n=a[l++],t[n]);return e}},function(e,t,n){var r=n(26),o=n(125).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],s=function(e){try{return o(e)}catch(t){return a.slice()}};e.exports.f=function(e){return a&&"[object Window]"==i.call(e)?s(e):o(r(e))}},function(e,t,n){var r=n(25),o=n(51),i=n(71)("IE_PROTO"),a=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},function(e,t,n){var r=n(16),o=n(11),i=n(31);e.exports=function(e,t){var n=(o.Object||{})[e]||Object[e],a={};a[e]=t(n),r(r.S+r.F*i(function(){n(1)}),"Object",a)}},function(e,t,n){var r=n(36),o=n(30),i=function(e,t){if(o(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{r=n(64)(Function.call,n(124).f(Object.prototype,"__proto__").set,2),r(e,[]),t=!(e instanceof Array)}catch(o){t=!0}return function(e,n){return i(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:i}},function(e,t,n){var r=n(73),o=n(65);e.exports=function(e){return function(t,n){var i,a,s=String(o(t)),l=r(n),u=s.length;return l<0||l>=u?e?"":void 0:(i=s.charCodeAt(l),i<55296||i>56319||l+1===u||(a=s.charCodeAt(l+1))<56320||a>57343?e?s.charAt(l):i:e?s.slice(l,l+2):(i-55296<<10)+(a-56320)+65536)}}},function(e,t,n){var r=n(73),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t,n){var r=n(327),o=n(13)("iterator"),i=n(37);e.exports=n(11).getIteratorMethod=function(e){if(void 0!=e)return e[o]||e["@@iterator"]||i[r(e)]}},function(e,t,n){"use strict";var r=n(64),o=n(16),i=n(51),a=n(333),s=n(331),l=n(128),u=n(328),c=n(347);o(o.S+o.F*!n(335)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,o,p,f=i(e),d="function"==typeof this?this:Array,h=arguments.length,y=h>1?arguments[1]:void 0,v=void 0!==y,m=0,g=c(f);if(v&&(y=r(y,h>2?arguments[2]:void 0,2)),void 0==g||d==Array&&s(g))for(t=l(f.length),n=new d(t);t>m;m++)u(n,m,v?y(f[m],m):f[m]);else for(p=g.call(f),n=new d;!(o=p.next()).done;m++)u(n,m,v?a(p,y,[o.value,m],!0):o.value);return n.length=m,n}})},function(e,t,n){"use strict";var r=n(325),o=n(336),i=n(37),a=n(26);e.exports=n(123)(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,o(1)):"keys"==t?o(0,n):"values"==t?o(0,e[n]):o(0,[n,e[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t,n){var r=n(16);r(r.S+r.F,"Object",{assign:n(339)})},function(e,t,n){var r=n(16);r(r.S,"Object",{create:n(68)})},function(e,t,n){var r=n(16);r(r.S+r.F*!n(24),"Object",{defineProperty:n(18).f})},function(e,t,n){var r=n(51),o=n(33);n(343)("keys",function(){return function(e){return o(r(e))}})},function(e,t,n){var r=n(16);r(r.S,"Object",{setPrototypeOf:n(344).set})},function(e,t){},function(e,t,n){"use strict";var r=n(17),o=n(25),i=n(24),a=n(16),s=n(127),l=n(338).KEY,u=n(31),c=n(72),p=n(70),f=n(52),d=n(13),h=n(76),y=n(75),v=n(337),m=n(329),g=n(332),b=n(30),P=n(26),C=n(74),T=n(38),O=n(68),w=n(341),x=n(124),E=n(18),S=n(33),k=x.f,N=E.f,j=w.f,_=r.Symbol,M=r.JSON,D=M&&M.stringify,A="prototype",L=d("_hidden"),V=d("toPrimitive"),I={}.propertyIsEnumerable,F=c("symbol-registry"),R=c("symbols"),K=c("op-symbols"),W=Object[A],H="function"==typeof _,z=r.QObject,U=!z||!z[A]||!z[A].findChild,B=i&&u(function(){return 7!=O(N({},"a",{get:function(){return N(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=k(W,t);r&&delete W[t],N(e,t,n),r&&e!==W&&N(W,t,r)}:N,Y=function(e){var t=R[e]=O(_[A]);return t._k=e,t},q=H&&"symbol"==typeof _.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof _},X=function(e,t,n){return e===W&&X(K,t,n),b(e),t=C(t,!0),b(n),o(R,t)?(n.enumerable?(o(e,L)&&e[L][t]&&(e[L][t]=!1),n=O(n,{enumerable:T(0,!1)})):(o(e,L)||N(e,L,T(1,{})),e[L][t]=!0),B(e,t,n)):N(e,t,n)},G=function(e,t){b(e);for(var n,r=m(t=P(t)),o=0,i=r.length;i>o;)X(e,n=r[o++],t[n]);return e},$=function(e,t){return void 0===t?O(e):G(O(e),t)},Q=function(e){var t=I.call(this,e=C(e,!0));return!(this===W&&o(R,e)&&!o(K,e))&&(!(t||!o(this,e)||!o(R,e)||o(this,L)&&this[L][e])||t)},Z=function(e,t){if(e=P(e),t=C(t,!0),e!==W||!o(R,t)||o(K,t)){var n=k(e,t);return!n||!o(R,t)||o(e,L)&&e[L][t]||(n.enumerable=!0),n}},J=function(e){for(var t,n=j(P(e)),r=[],i=0;n.length>i;)o(R,t=n[i++])||t==L||t==l||r.push(t);return r},ee=function(e){for(var t,n=e===W,r=j(n?K:P(e)),i=[],a=0;r.length>a;)!o(R,t=r[a++])||n&&!o(W,t)||i.push(R[t]);return i};H||(_=function(){if(this instanceof _)throw TypeError("Symbol is not a constructor!");var e=f(arguments.length>0?arguments[0]:void 0),t=function(n){this===W&&t.call(K,n),o(this,L)&&o(this[L],e)&&(this[L][e]=!1),B(this,e,T(1,n))};return i&&U&&B(W,e,{configurable:!0,set:t}),Y(e)},s(_[A],"toString",function(){return this._k}),x.f=Z,E.f=X,n(125).f=w.f=J,n(50).f=Q,n(69).f=ee,i&&!n(67)&&s(W,"propertyIsEnumerable",Q,!0),h.f=function(e){return Y(d(e))}),a(a.G+a.W+a.F*!H,{Symbol:_});for(var te="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ne=0;te.length>ne;)d(te[ne++]);for(var te=S(d.store),ne=0;te.length>ne;)y(te[ne++]);a(a.S+a.F*!H,"Symbol",{"for":function(e){return o(F,e+="")?F[e]:F[e]=_(e)},keyFor:function(e){if(q(e))return v(F,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){U=!0},useSimple:function(){U=!1}}),a(a.S+a.F*!H,"Object",{create:$,defineProperty:X,defineProperties:G,getOwnPropertyDescriptor:Z,getOwnPropertyNames:J,getOwnPropertySymbols:ee}),M&&a(a.S+a.F*(!H||u(function(){var e=_();return"[null]"!=D([e])||"{}"!=D({a:e})||"{}"!=D(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!q(e)){for(var t,n,r=[e],o=1;arguments.length>o;)r.push(arguments[o++]);return t=r[1],"function"==typeof t&&(n=t),!n&&g(t)||(t=function(e,t){if(n&&(t=n.call(this,e,t)),!q(t))return t}),r[1]=t,D.apply(M,r)}}}),_[A][V]||n(32)(_[A],V,_[A].valueOf),p(_,"Symbol"),p(Math,"Math",!0),p(r.JSON,"JSON",!0)},function(e,t,n){n(75)("asyncIterator")},function(e,t,n){n(75)("observable")},function(e,t,n){n(349);for(var r=n(17),o=n(32),i=n(37),a=n(13)("toStringTag"),s=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],l=0;l<5;l++){var u=s[l],c=r[u],p=c&&c.prototype;p&&!p[a]&&o(p,a,u),i[u]=i.Array}},function(e,t){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete i.animationend.animation,"TransitionEvent"in window||delete i.transitionend.transition;for(var n in i)if(i.hasOwnProperty(n)){var r=i[n];for(var o in r)if(o in t){a.push(r[o]);break}}}function r(e,t,n){e.addEventListener(t,n,!1)}function o(e,t,n){e.removeEventListener(t,n,!1)}Object.defineProperty(t,"__esModule",{value:!0});var i={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},a=[];"undefined"!=typeof window&&"undefined"!=typeof document&&n();var s={addEndEventListener:function(e,t){return 0===a.length?void window.setTimeout(t,0):void a.forEach(function(n){r(e,n,t)})},endEvents:a,removeEndEventListener:function(e,t){0!==a.length&&a.forEach(function(n){o(e,n,t)})}};t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r){var o=a["default"].clone(e),i={width:t.width,height:t.height};return r.adjustX&&o.left<n.left&&(o.left=n.left),r.resizeWidth&&o.left>=n.left&&o.left+i.width>n.right&&(i.width-=o.left+i.width-n.right),r.adjustX&&o.left+i.width>n.right&&(o.left=Math.max(n.right-i.width,n.left)),r.adjustY&&o.top<n.top&&(o.top=n.top),r.resizeHeight&&o.top>=n.top&&o.top+i.height>n.bottom&&(i.height-=o.top+i.height-n.bottom),r.adjustY&&o.top+i.height>n.bottom&&(o.top=Math.max(n.bottom-i.height,n.top)),a["default"].mix(o,i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(39),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=t.charAt(0),r=t.charAt(1),o=e.width,i=e.height,a=void 0,s=void 0;return a=e.left,s=e.top,"c"===n?s+=i/2:"b"===n&&(s+=i),"c"===r?a+=o/2:"r"===r&&(a+=o),{left:a,top:s}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=void 0,s=void 0,l=void 0,u=void 0;return i={left:e.left,top:e.top},l=(0,a["default"])(t,n[1]),u=(0,a["default"])(e,n[0]),s=[u.left-l.left,u.top-l.top],{left:i.left-s[0]+r[0]-o[0],top:i.top-s[1]+r[1]-o[1]}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(362),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=void 0,n=void 0,r=void 0;if(a["default"].isWindow(e)||9===e.nodeType){var o=a["default"].getWindow(e);t={left:a["default"].getWindowScrollLeft(o),top:a["default"].getWindowScrollTop(o)},n=a["default"].viewportWidth(o),r=a["default"].viewportHeight(o)}else t=a["default"].offset(e),n=a["default"].outerWidth(e),r=a["default"].outerHeight(e);return t.width=n,t.height=r,t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(39),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){for(var t={left:0,right:1/0,top:0,bottom:1/0},n=(0,l["default"])(e),r=void 0,o=void 0,i=void 0,s=e.ownerDocument,u=s.defaultView||s.parentWindow,c=s.body,p=s.documentElement;n;){if(navigator.userAgent.indexOf("MSIE")!==-1&&0===n.clientWidth||n===c||n===p||"visible"===a["default"].css(n,"overflow")){if(n===c||n===p)break}else{var f=a["default"].offset(n);f.left+=n.clientLeft,f.top+=n.clientTop,t.top=Math.max(t.top,f.top),t.right=Math.min(t.right,f.left+n.clientWidth),t.bottom=Math.min(t.bottom,f.top+n.clientHeight),t.left=Math.max(t.left,f.left)}n=(0,l["default"])(n)}return r=a["default"].getWindowScrollLeft(u),o=a["default"].getWindowScrollTop(u),t.left=Math.max(t.left,r),t.top=Math.max(t.top,o),i={width:a["default"].viewportWidth(u),height:a["default"].viewportHeight(u)},t.right=Math.min(t.right,r+i.width),t.bottom=Math.min(t.bottom,o+i.height),t.top>=0&&t.left>=0&&t.bottom>t.top&&t.right>t.left?t:null}Object.defineProperty(t,"__esModule",{value:!0});var i=n(39),a=r(i),s=n(130),l=r(s);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return e.left<n.left||e.left+t.width>n.right}function i(e,t,n){return e.top<n.top||e.top+t.height>n.bottom}function a(e,t,n){return e.left>n.right||e.left+t.width<n.left}function s(e,t,n){return e.top>n.bottom||e.top+t.height<n.top}function l(e,t,n){var r=[];return h["default"].each(e,function(e){r.push(e.replace(t,function(e){return n[e]}))}),r}function u(e,t){return e[t]=-e[t],e}function c(e,t){var n=void 0;return n=/%$/.test(e)?parseInt(e.substring(0,e.length-1),10)/100*t:parseInt(e,10),n||0}function p(e,t){e[0]=c(e[0],t.width),e[1]=c(e[1],t.height)}function f(e,t,n){var r=n.points,c=n.offset||[0,0],f=n.targetOffset||[0,0],d=n.overflow,y=n.target||t,v=n.source||e;c=[].concat(c),f=[].concat(f),d=d||{};var m={},b=0,C=(0,g["default"])(v),O=(0,T["default"])(v),x=(0,T["default"])(y);p(c,O),p(f,x);var E=(0,w["default"])(O,x,r,c,f),S=h["default"].merge(O,E);if(C&&(d.adjustX||d.adjustY)){if(d.adjustX&&o(E,O,C)){var k=l(r,/[lr]/gi,{l:"r",r:"l"}),N=u(c,0),j=u(f,0),_=(0,w["default"])(O,x,k,N,j);a(_,O,C)||(b=1,r=k,c=N,f=j)}if(d.adjustY&&i(E,O,C)){var M=l(r,/[tb]/gi,{t:"b",b:"t"}),D=u(c,1),A=u(f,1),L=(0,w["default"])(O,x,M,D,A);s(L,O,C)||(b=1,r=M,c=D,f=A)}b&&(E=(0,w["default"])(O,x,r,c,f),h["default"].mix(S,E)),m.adjustX=d.adjustX&&o(E,O,C),m.adjustY=d.adjustY&&i(E,O,C),(m.adjustX||m.adjustY)&&(S=(0,P["default"])(E,O,C,m))}return S.width!==O.width&&h["default"].css(v,"width",h["default"].width(v)+S.width-O.width),S.height!==O.height&&h["default"].css(v,"height",h["default"].height(v)+S.height-O.height),h["default"].offset(v,{left:S.left,top:S.top},{useCssRight:n.useCssRight,useCssBottom:n.useCssBottom,useCssTransform:n.useCssTransform}),{points:r,offset:c,targetOffset:f,overflow:m}}Object.defineProperty(t,"__esModule",{value:!0});var d=n(39),h=r(d),y=n(130),v=r(y),m=n(365),g=r(m),b=n(361),P=r(b),C=n(364),T=r(C),O=n(363),w=r(O);f.__getOffsetParent=v["default"],f.__getVisibleRectForElement=g["default"],t["default"]=f,e.exports=t["default"]},function(e,t){"use strict";function n(){if(void 0!==c)return c;c="";var e=document.createElement("p").style,t="Transform";for(var n in p)n+t in e&&(c=n);return c}function r(){return n()?n()+"TransitionProperty":"transitionProperty"}function o(){return n()?n()+"Transform":"transform"}function i(e,t){var n=r();n&&(e.style[n]=t,"transitionProperty"!==n&&(e.style.transitionProperty=t))}function a(e,t){var n=o();n&&(e.style[n]=t,"transform"!==n&&(e.style.transform=t))}function s(e){return e.style.transitionProperty||e.style[r()]}function l(e){var t=window.getComputedStyle(e,null),n=t.getPropertyValue("transform")||t.getPropertyValue(o());if(n&&"none"!==n){var r=n.replace(/[^0-9\-.,]/g,"").split(",");return{x:parseFloat(r[12]||r[4],0),y:parseFloat(r[13]||r[5],0)}}return{x:0,y:0}}function u(e,t){var n=window.getComputedStyle(e,null),r=n.getPropertyValue("transform")||n.getPropertyValue(o());if(r&&"none"!==r){var i=void 0,s=r.match(f);if(s)s=s[1],i=s.split(",").map(function(e){return parseFloat(e,10)}),i[4]=t.x,i[5]=t.y,a(e,"matrix("+i.join(",")+")");else{var l=r.match(d)[1];i=l.split(",").map(function(e){return parseFloat(e,10)}),i[12]=t.x,i[13]=t.y,a(e,"matrix3d("+i.join(",")+")")}}else a(e,"translateX("+t.x+"px) translateY("+t.y+"px) translateZ(0)")}Object.defineProperty(t,"__esModule",{value:!0}),t.getTransformName=o,t.setTransitionProperty=i,t.getTransitionProperty=s,t.getTransformXY=l,t.setTransformXY=u;var c=void 0,p={Webkit:"-webkit-",Moz:"-moz-",ms:"-ms-",O:"-o-"},f=/matrix\((.*)\)/,d=/matrix3d\((.*)\)/},function(e,t,n){"use strict";function r(e,t,n){n=n||{},9===t.nodeType&&(t=o.getWindow(t));var r=n.allowHorizontalScroll,i=n.onlyScrollIfNeeded,a=n.alignWithTop,s=n.alignWithLeft,l=n.offsetTop||0,u=n.offsetLeft||0,c=n.offsetBottom||0,p=n.offsetRight||0;r=void 0===r||r;var f=o.isWindow(t),d=o.offset(e),h=o.outerHeight(e),y=o.outerWidth(e),v=void 0,m=void 0,g=void 0,b=void 0,P=void 0,C=void 0,T=void 0,O=void 0,w=void 0,x=void 0;f?(T=t,x=o.height(T),w=o.width(T),O={left:o.scrollLeft(T),top:o.scrollTop(T)},P={left:d.left-O.left-u,top:d.top-O.top-l},C={left:d.left+y-(O.left+w)+p,top:d.top+h-(O.top+x)+c },b=O):(v=o.offset(t),m=t.clientHeight,g=t.clientWidth,b={left:t.scrollLeft,top:t.scrollTop},P={left:d.left-(v.left+(parseFloat(o.css(t,"borderLeftWidth"))||0))-u,top:d.top-(v.top+(parseFloat(o.css(t,"borderTopWidth"))||0))-l},C={left:d.left+y-(v.left+g+(parseFloat(o.css(t,"borderRightWidth"))||0))+p,top:d.top+h-(v.top+m+(parseFloat(o.css(t,"borderBottomWidth"))||0))+c}),P.top<0||C.top>0?a===!0?o.scrollTop(t,b.top+P.top):a===!1?o.scrollTop(t,b.top+C.top):P.top<0?o.scrollTop(t,b.top+P.top):o.scrollTop(t,b.top+C.top):i||(a=void 0===a||!!a,a?o.scrollTop(t,b.top+P.top):o.scrollTop(t,b.top+C.top)),r&&(P.left<0||C.left>0?s===!0?o.scrollLeft(t,b.left+P.left):s===!1?o.scrollLeft(t,b.left+C.left):P.left<0?o.scrollLeft(t,b.left+P.left):o.scrollLeft(t,b.left+C.left):i||(s=void 0===s||!!s,s?o.scrollLeft(t,b.left+P.left):o.scrollLeft(t,b.left+C.left)))}var o=n(369);e.exports=r},function(e,t){"use strict";function n(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,i=o.body,a=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=a.clientLeft||i.clientLeft||0,r-=a.clientTop||i.clientTop||0,{left:n,top:r}}function r(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function o(e){return r(e)}function i(e){return r(e,!0)}function a(e){var t=n(e),r=e.ownerDocument,a=r.defaultView||r.parentWindow;return t.left+=o(a),t.top+=i(a),t}function s(e,t,n){var r="",o=e.ownerDocument,i=n||o.defaultView.getComputedStyle(e,null);return i&&(r=i.getPropertyValue(t)||i[t]),r}function l(e,t){var n=e[O]&&e[O][t];if(C.test(n)&&!T.test(t)){var r=e.style,o=r[x],i=e[w][x];e[w][x]=e[O][x],r[x]="fontSize"===t?"1em":n||0,n=r.pixelLeft+E,r[x]=o,e[w][x]=i}return""===n?"auto":n}function u(e,t){for(var n=0;n<e.length;n++)t(e[n])}function c(e){return"border-box"===S(e,"boxSizing")}function p(e,t,n){var r={},o=e.style,i=void 0;for(i in t)t.hasOwnProperty(i)&&(r[i]=o[i],o[i]=t[i]);n.call(e);for(i in t)t.hasOwnProperty(i)&&(o[i]=r[i])}function f(e,t,n){var r=0,o=void 0,i=void 0,a=void 0;for(i=0;i<t.length;i++)if(o=t[i])for(a=0;a<n.length;a++){var s=void 0;s="border"===o?o+n[a]+"Width":o+n[a],r+=parseFloat(S(e,s))||0}return r}function d(e){return null!=e&&e==e.window}function h(e,t,n){if(d(e))return"width"===t?D.viewportWidth(e):D.viewportHeight(e);if(9===e.nodeType)return"width"===t?D.docWidth(e):D.docHeight(e);var r="width"===t?["Left","Right"]:["Top","Bottom"],o="width"===t?e.offsetWidth:e.offsetHeight,i=S(e),a=c(e,i),s=0;(null==o||o<=0)&&(o=void 0,s=S(e,t),(null==s||Number(s)<0)&&(s=e.style[t]||0),s=parseFloat(s)||0),void 0===n&&(n=a?_:N);var l=void 0!==o||a,u=o||s;if(n===N)return l?u-f(e,["border","padding"],r,i):s;if(l){var p=n===j?-f(e,["border"],r,i):f(e,["margin"],r,i);return u+(n===_?0:p)}return s+f(e,k.slice(n),r,i)}function y(e){var t=void 0,n=arguments;return 0!==e.offsetWidth?t=h.apply(void 0,n):p(e,A,function(){t=h.apply(void 0,n)}),t}function v(e,t,n){var r=n;{if("object"!==("undefined"==typeof t?"undefined":b(t)))return"undefined"!=typeof r?("number"==typeof r&&(r+="px"),void(e.style[t]=r)):S(e,t);for(var o in t)t.hasOwnProperty(o)&&v(e,o,t[o])}}function m(e,t){"static"===v(e,"position")&&(e.style.position="relative");var n=a(e),r={},o=void 0,i=void 0;for(i in t)t.hasOwnProperty(i)&&(o=parseFloat(v(e,i))||0,r[i]=o+t[i]-n[i]);v(e,r)}var g=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},b="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},P=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,C=new RegExp("^("+P+")(?!px)[a-z%]+$","i"),T=/^(top|right|bottom|left)$/,O="currentStyle",w="runtimeStyle",x="left",E="px",S=void 0;"undefined"!=typeof window&&(S=window.getComputedStyle?s:l);var k=["margin","border","padding"],N=-1,j=2,_=1,M=0,D={};u(["Width","Height"],function(e){D["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],D["viewport"+e](n))},D["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,i=r.documentElement,a=i[n];return"CSS1Compat"===r.compatMode&&a||o&&o[n]||a}});var A={position:"absolute",visibility:"hidden",display:"block"};u(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);D["outer"+t]=function(t,n){return t&&y(t,e,n?M:_)};var n="width"===e?["Left","Right"]:["Top","Bottom"];D[e]=function(t,r){if(void 0===r)return t&&y(t,e,N);if(t){var o=S(t),i=c(t);return i&&(r+=f(t,["padding","border"],n,o)),v(t,e,r)}}}),e.exports=g({getWindow:function(e){var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},offset:function(e,t){return"undefined"==typeof t?a(e):void m(e,t)},isWindow:d,each:u,css:v,clone:function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);var r=e.overflow;if(r)for(var n in e)e.hasOwnProperty(n)&&(t.overflow[n]=e.overflow[n]);return t},scrollLeft:function(e,t){if(d(e)){if(void 0===t)return o(e);window.scrollTo(t,i(e))}else{if(void 0===t)return e.scrollLeft;e.scrollLeft=t}},scrollTop:function(e,t){if(d(e)){if(void 0===t)return i(e);window.scrollTo(o(e),t)}else{if(void 0===t)return e.scrollTop;e.scrollTop=t}},viewportWidth:0,viewportHeight:0},D)},function(e,t,n){var r;!function(o,i,a){var s=window.matchMedia;"undefined"!=typeof e&&e.exports?e.exports=a(s):(r=function(){return i[o]=a(s)}.call(t,n,t,e),!(void 0!==r&&(e.exports=r)))}("enquire",this,function(e){"use strict";function t(e,t){var n,r=0,o=e.length;for(r;r<o&&(n=t(e[r],r),n!==!1);r++);}function n(e){return"[object Array]"===Object.prototype.toString.apply(e)}function r(e){return"function"==typeof e}function o(e){this.options=e,!e.deferSetup&&this.setup()}function i(t,n){this.query=t,this.isUnconditional=n,this.handlers=[],this.mql=e(t);var r=this;this.listener=function(e){r.mql=e,r.assess()},this.mql.addListener(this.listener)}function a(){if(!e)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!e("only all").matches}return o.prototype={setup:function(){this.options.setup&&this.options.setup(),this.initialised=!0},on:function(){!this.initialised&&this.setup(),this.options.match&&this.options.match()},off:function(){this.options.unmatch&&this.options.unmatch()},destroy:function(){this.options.destroy?this.options.destroy():this.off()},equals:function(e){return this.options===e||this.options.match===e}},i.prototype={addHandler:function(e){var t=new o(e);this.handlers.push(t),this.matches()&&t.on()},removeHandler:function(e){var n=this.handlers;t(n,function(t,r){if(t.equals(e))return t.destroy(),!n.splice(r,1)})},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){t(this.handlers,function(e){e.destroy()}),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var e=this.matches()?"on":"off";t(this.handlers,function(t){t[e]()})}},a.prototype={register:function(e,o,a){var s=this.queries,l=a&&this.browserIsIncapable;return s[e]||(s[e]=new i(e,l)),r(o)&&(o={match:o}),n(o)||(o=[o]),t(o,function(t){s[e].addHandler(t)}),this},unregister:function(e,t){var n=this.queries[e];return n&&(t?n.removeHandler(t):(n.clear(),delete this.queries[e])),this}},new a})},function(e,t){"use strict";function n(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function r(e,t){if(n(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(var a=0;a<r.length;a++)if(!o.call(t,r[a])||!n(e[r[a]],t[r[a]]))return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=r},function(e,t){/*! * for-in <https://github.com/jonschlinkert/for-in> * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ "use strict";e.exports=function(e,t,n){for(var r in e)if(t.call(n,e[r],r,e)===!1)break}},function(e,t,n){/*! * for-own <https://github.com/jonschlinkert/for-own> * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ "use strict";var r=n(372),o=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){r(e,function(r,i){if(o.call(e,i))return t.call(n,e[i],i,e)})}},22,function(e,t,n){"use strict";function r(e,t,n){return n+(h.isLeapYear(e)?u[t]:l[t])}function o(e){return e>=0?e%7:h.mod(e,7)}function i(e){var t=void 0,n=void 0,r=void 0,o=void 0,i=void 0,a=void 0,l=void 0,u=void 0,y=void 0;return t=e-1,i=s(t/d),n=h.mod(t,d),a=s(n/f),r=h.mod(n,f),l=s(r/p),o=h.mod(r,p),u=s(o/c),y=400*i+100*a+4*l+u,4!==a&&4!==u&&++y,y}var a=n(132),s=Math.floor,l=[0,31,59,90,120,151,181,212,243,273,304,334],u=[0,31,60,91,121,152,182,213,244,274,305,335],c=365,p=1461,f=25*p-1,d=4*f+1,h={};h=e.exports={each:function(e,t){for(var n=0,r=e.length;n<r&&t(e[n],n,e)!==!1;n++);},mix:function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},isLeapYear:function(e){return 0===(3&e)&&(e%100!==0||e%400===0)},mod:function(e,t){return e-t*s(e/t)},getFixedDate:function(e,t,n){var o=e-1;return c*o+s(o/4)-s(o/100)+s(o/400)+r(e,t,n)},getGregorianDateFromFixedDate:function(e){for(var t=i(e),n=h.getFixedDate(t,a.JANUARY,1),r=h.isLeapYear(t),s=r?u:l,c=e-n,p=void 0,f=0;f<s.length&&s[f]<=c;f++)p=f;var d=e-n-s[p]+1,y=o(e);return{year:t,month:p,dayOfMonth:d,dayOfWeek:y,isLeap:r}}}},function(e,t){"use strict";var n={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},r={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,i){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);o&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var s=0;s<a.length;++s)if(!(n[a[s]]||r[a[s]]||i&&i[a[s]]))try{e[a[s]]=t[a[s]]}catch(l){}}return e}},function(e,t){/*! * is-extendable <https://github.com/jonschlinkert/is-extendable> * * Copyright (c) 2015, Jon Schlinkert. * Licensed under the MIT License. */ "use strict";e.exports=function(e){return"undefined"!=typeof e&&null!==e&&("object"==typeof e||"function"==typeof e)}},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return a(n)?n:void 0}function o(e){return i(e)&&f.call(e)==s}function i(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function a(e){return null!=e&&(o(e)?d.test(c.call(e)):n(e)&&l.test(e))}var s="[object Function]",l=/^\[object .+?Constructor\]$/,u=Object.prototype,c=Function.prototype.toString,p=u.hasOwnProperty,f=u.toString,d=RegExp("^"+c.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t){function n(e){return o(e)&&h.call(e,"callee")&&(!v.call(e,"callee")||y.call(e)==c)}function r(e){return null!=e&&a(e.length)&&!i(e)}function o(e){return l(e)&&r(e)}function i(e){var t=s(e)?y.call(e):"";return t==p||t==f}function a(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=u}function s(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function l(e){return!!e&&"object"==typeof e}var u=9007199254740991,c="[object Arguments]",p="[object Function]",f="[object GeneratorFunction]",d=Object.prototype,h=d.hasOwnProperty,y=d.toString,v=d.propertyIsEnumerable;e.exports=n},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return s(n)?n:void 0}function o(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=m}function i(e){return a(e)&&h.call(e)==u}function a(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function s(e){return null!=e&&(i(e)?y.test(f.call(e)):n(e)&&c.test(e))}var l="[object Array]",u="[object Function]",c=/^\[object .+?Constructor\]$/,p=Object.prototype,f=Function.prototype.toString,d=p.hasOwnProperty,h=p.toString,y=RegExp("^"+f.call(d).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),v=r(Array,"isArray"),m=9007199254740991,g=v||function(e){return n(e)&&o(e.length)&&h.call(e)==l};e.exports=g},function(e,t,n){function r(e){return function(t){return null==t?void 0:t[e]}}function o(e){return null!=e&&a(g(e))}function i(e,t){return e="number"==typeof e||d.test(e)?+e:-1,t=null==t?m:t,e>-1&&e%1==0&&e<t}function a(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=m}function s(e){for(var t=u(e),n=t.length,r=n&&e.length,o=!!r&&a(r)&&(f(e)||p(e)),s=-1,l=[];++s<n;){var c=t[s];(o&&i(c,r)||y.call(e,c))&&l.push(c)}return l}function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function u(e){if(null==e)return[];l(e)||(e=Object(e));var t=e.length;t=t&&a(t)&&(f(e)||p(e))&&t||0;for(var n=e.constructor,r=-1,o="function"==typeof n&&n.prototype===e,s=Array(t),u=t>0;++r<t;)s[r]=r+"";for(var c in e)u&&i(c,t)||"constructor"==c&&(o||!y.call(e,c))||s.push(c);return s}var c=n(378),p=n(379),f=n(380),d=/^\d+$/,h=Object.prototype,y=h.hasOwnProperty,v=c(Object,"keys"),m=9007199254740991,g=r("length"),b=v?function(e){var t=null==e?void 0:e.constructor;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&o(e)?s(e):l(e)?v(e):[]}:s;e.exports=b},function(e,t,n){var r,o,i;!function(n,a){"use strict";"object"==typeof e&&"object"==typeof e.exports?e.exports=a():(o=[],r=a,i="function"==typeof r?r.apply(t,o):r,!(void 0!==i&&(e.exports=i)))}(this,function(){"use strict";function e(e,t){return null!=e&&Object.prototype.hasOwnProperty.call(e,t)}function t(t){if(!t)return!0;if(l(t)&&0===t.length)return!0;if("string"!=typeof t){for(var n in t)if(e(t,n))return!1;return!0}return!1}function n(e){return s.call(e)}function r(e){return"object"==typeof e&&"[object Object]"===n(e)}function o(e){return"boolean"==typeof e||"[object Boolean]"===n(e)}function i(e){var t=parseInt(e);return t.toString()===e?t:e}function a(n){function a(t,r){if(n.includeInheritedProps||"number"==typeof r&&Array.isArray(t)||e(t,r))return t[r]}function s(e,t,n,r){if("number"==typeof t&&(t=[t]),!t||0===t.length)return e;if("string"==typeof t)return s(e,t.split(".").map(i),n,r);var o=t[0],l=a(e,o);return 1===t.length?(void 0!==l&&r||(e[o]=n),l):(void 0===l&&("number"==typeof t[1]?e[o]=[]:e[o]={}),s(e[o],t.slice(1),n,r))}n=n||{};var u=function(e){return Object.keys(u).reduce(function(t,n){return"create"===n?t:("function"==typeof u[n]&&(t[n]=u[n].bind(u,e)),t)},{})};return u.has=function(t,r){if("number"==typeof r?r=[r]:"string"==typeof r&&(r=r.split(".")),!r||0===r.length)return!!t;for(var o=0;o<r.length;o++){var a=i(r[o]);if(!("number"==typeof a&&l(t)&&a<t.length||(n.includeInheritedProps?a in Object(t):e(t,a))))return!1;t=t[a]}return!0},u.ensureExists=function(e,t,n){return s(e,t,n,!0)},u.set=function(e,t,n,r){return s(e,t,n,r)},u.insert=function(e,t,n,r){var o=u.get(e,t);r=~~r,l(o)||(o=[],u.set(e,t,o)),o.splice(r,0,n)},u.empty=function(n,i){if(!t(i)&&null!=n){var a,s;if(a=u.get(n,i)){if("string"==typeof a)return u.set(n,i,"");if(o(a))return u.set(n,i,!1);if("number"==typeof a)return u.set(n,i,0);if(l(a))a.length=0;else{if(!r(a))return u.set(n,i,null);for(s in a)e(a,s)&&delete a[s]}}}},u.push=function(e,t){var n=u.get(e,t);l(n)||(n=[],u.set(e,t,n)),n.push.apply(n,Array.prototype.slice.call(arguments,2))},u.coalesce=function(e,t,n){for(var r,o=0,i=t.length;o<i;o++)if(void 0!==(r=u.get(e,t[o])))return r;return n},u.get=function(e,t,n){if("number"==typeof t&&(t=[t]),!t||0===t.length)return e;if(null==e)return n;if("string"==typeof t)return u.get(e,t.split("."),n);var r=i(t[0]),o=a(e,r);return void 0===o?n:1===t.length?o:u.get(e[r],t.slice(1),n)},u.del=function(e,n){if("number"==typeof n&&(n=[n]),null==e)return e;if(t(n))return e;if("string"==typeof n)return u.del(e,n.split("."));var r=i(n[0]),o=a(e,r);if(null==o)return o;if(1===n.length)l(e)?e.splice(r,1):delete e[r];else if(void 0!==e[r])return u.del(e[r],n.slice(1));return e},u}var s=Object.prototype.toString,l=Array.isArray||function(e){return"[object Array]"===s.call(e)},u=a();return u.create=a,u.withInheritedProps=a({includeInheritedProps:!0}),u})},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(e){if(c===setTimeout)return setTimeout(e,0);if((c===n||!c)&&setTimeout)return c=setTimeout,setTimeout(e,0);try{return c(e,0)}catch(t){try{return c.call(null,e,0)}catch(t){return c.call(this,e,0)}}}function i(e){if(p===clearTimeout)return clearTimeout(e);if((p===r||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function a(){y&&d&&(y=!1,d.length?h=d.concat(h):v=-1,h.length&&s())}function s(){if(!y){var e=o(a);y=!0;for(var t=h.length;t;){for(d=h,h=[];++v<t;)d&&d[v].run();v=-1,t=h.length}d=null,y=!1,i(e)}}function l(e,t){this.fun=e,this.array=t}function u(){}var c,p,f=e.exports={};!function(){try{c="function"==typeof setTimeout?setTimeout:n}catch(e){c=n}try{p="function"==typeof clearTimeout?clearTimeout:r}catch(e){p=r}}();var d,h=[],y=!1,v=-1;f.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];h.push(new l(e,t)),1!==h.length||y||o(s)},l.prototype.run=function(){this.fun.apply(null,this.array)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=u,f.addListener=u,f.once=u,f.off=u,f.removeListener=u,f.removeAllListeners=u,f.emit=u,f.binding=function(e){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(e){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){function n(){o&&(clearTimeout(o),o=null)}function r(){n(),o=setTimeout(e,t)}var o=void 0;return r.clear=n,r}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=n(4),l=r(s),u=n(366),c=r(u),p=n(20),f=r(p),d=n(386),h=r(d),y=a["default"].createClass({displayName:"Align",propTypes:{childrenProps:i.PropTypes.object,align:i.PropTypes.object.isRequired,target:i.PropTypes.func,onAlign:i.PropTypes.func,monitorBufferTime:i.PropTypes.number,monitorWindowResize:i.PropTypes.bool,disabled:i.PropTypes.bool,children:i.PropTypes.any},getDefaultProps:function(){return{target:function(){return window},onAlign:function(){},monitorBufferTime:50,monitorWindowResize:!1,disabled:!1}},componentDidMount:function(){var e=this.props;this.forceAlign(),!e.disabled&&e.monitorWindowResize&&this.startMonitorWindowResize()},componentDidUpdate:function(e){var t=!1,n=this.props;if(!n.disabled)if(e.disabled||e.align!==n.align)t=!0;else{var r=e.target(),o=n.target();(0,h["default"])(r)&&(0,h["default"])(o)?t=!1:r!==o&&(t=!0)}t&&this.forceAlign(),n.monitorWindowResize&&!n.disabled?this.startMonitorWindowResize():this.stopMonitorWindowResize()},componentWillUnmount:function(){this.stopMonitorWindowResize()},startMonitorWindowResize:function(){this.resizeHandler||(this.bufferMonitor=o(this.forceAlign,this.props.monitorBufferTime),this.resizeHandler=(0,f["default"])(window,"resize",this.bufferMonitor))},stopMonitorWindowResize:function(){this.resizeHandler&&(this.bufferMonitor.clear(),this.resizeHandler.remove(),this.resizeHandler=null)},forceAlign:function(){var e=this.props;if(!e.disabled){var t=l["default"].findDOMNode(this);e.onAlign(t,(0,c["default"])(t,e.target(),e.align))}},render:function(){var e=this.props,t=e.childrenProps,n=e.children,r=a["default"].Children.only(n);if(t){var o={};for(var i in t)t.hasOwnProperty(i)&&(o[i]=this.props[t[i]]);return a["default"].cloneElement(r,o)}return r}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(384),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t){"use strict";function n(e){return null!=e&&e==e.window}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=e.children;return l["default"].isValidElement(t)&&!t.key?l["default"].cloneElement(t,{key:h}):t}function a(){}Object.defineProperty(t,"__esModule",{value:!0});var s=n(1),l=r(s),u=n(389),c=n(388),p=r(c),f=n(136),d=r(f),h="rc_animate_"+Date.now(),y=l["default"].createClass({displayName:"Animate",propTypes:{component:l["default"].PropTypes.any,animation:l["default"].PropTypes.object,transitionName:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.object]),transitionEnter:l["default"].PropTypes.bool,transitionAppear:l["default"].PropTypes.bool,exclusive:l["default"].PropTypes.bool,transitionLeave:l["default"].PropTypes.bool,onEnd:l["default"].PropTypes.func,onEnter:l["default"].PropTypes.func,onLeave:l["default"].PropTypes.func,onAppear:l["default"].PropTypes.func,showProp:l["default"].PropTypes.string},getDefaultProps:function(){return{animation:{},component:"span",transitionEnter:!0,transitionLeave:!0,transitionAppear:!1,onEnd:a,onEnter:a,onLeave:a,onAppear:a}},getInitialState:function(){return this.currentlyAnimatingKeys={},this.keysToEnter=[],this.keysToLeave=[],{children:(0,u.toArrayChildren)(i(this.props))}},componentDidMount:function(){var e=this,t=this.props.showProp,n=this.state.children;t&&(n=n.filter(function(e){return!!e.props[t]})),n.forEach(function(t){t&&e.performAppear(t.key)})},componentWillReceiveProps:function(e){var t=this;this.nextProps=e;var n=(0,u.toArrayChildren)(i(e)),r=this.props;r.exclusive&&Object.keys(this.currentlyAnimatingKeys).forEach(function(e){t.stop(e)});var a=r.showProp,s=this.currentlyAnimatingKeys,c=r.exclusive?(0,u.toArrayChildren)(i(r)):this.state.children,p=[];a?(c.forEach(function(e){var t=e&&(0,u.findChildInChildrenByKey)(n,e.key),r=void 0;r=t&&t.props[a]||!e.props[a]?t:l["default"].cloneElement(t||e,o({},a,!0)),r&&p.push(r)}),n.forEach(function(e){e&&(0,u.findChildInChildrenByKey)(c,e.key)||p.push(e)})):p=(0,u.mergeChildren)(c,n),this.setState({children:p}),n.forEach(function(e){var n=e&&e.key;if(!e||!s[n]){var r=e&&(0,u.findChildInChildrenByKey)(c,n);if(a){var o=e.props[a];if(r){var i=(0,u.findShownChildInChildrenByKey)(c,n,a);!i&&o&&t.keysToEnter.push(n)}else o&&t.keysToEnter.push(n)}else r||t.keysToEnter.push(n)}}),c.forEach(function(e){var r=e&&e.key;if(!e||!s[r]){var o=e&&(0,u.findChildInChildrenByKey)(n,r);if(a){var i=e.props[a];if(o){var l=(0,u.findShownChildInChildrenByKey)(n,r,a);!l&&i&&t.keysToLeave.push(r)}else i&&t.keysToLeave.push(r)}else o||t.keysToLeave.push(r)}})},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performEnter:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillEnter(this.handleDoneAdding.bind(this,e,"enter")))},performAppear:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillAppear(this.handleDoneAdding.bind(this,e,"appear")))},handleDoneAdding:function(e,t){var n=this.props;if(delete this.currentlyAnimatingKeys[e],!n.exclusive||n===this.nextProps){var r=(0,u.toArrayChildren)(i(n));this.isValidChildByKey(r,e)?"appear"===t?d["default"].allowAppearCallback(n)&&(n.onAppear(e),n.onEnd(e,!0)):d["default"].allowEnterCallback(n)&&(n.onEnter(e),n.onEnd(e,!0)):this.performLeave(e)}},performLeave:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillLeave(this.handleDoneLeaving.bind(this,e)))},handleDoneLeaving:function(e){var t=this.props;if(delete this.currentlyAnimatingKeys[e],!t.exclusive||t===this.nextProps){var n=(0,u.toArrayChildren)(i(t));if(this.isValidChildByKey(n,e))this.performEnter(e);else{var r=function(){d["default"].allowLeaveCallback(t)&&(t.onLeave(e),t.onEnd(e,!1))};this.isMounted()&&!(0,u.isSameChildren)(this.state.children,n,t.showProp)?this.setState({children:n},r):r()}}},isValidChildByKey:function(e,t){var n=this.props.showProp;return n?(0,u.findShownChildInChildrenByKey)(e,t,n):(0,u.findChildInChildrenByKey)(e,t)},stop:function(e){delete this.currentlyAnimatingKeys[e];var t=this.refs[e];t&&t.stop()},render:function(){var e=this.props;this.nextProps=e;var t=this.state.children,n=null;t&&(n=t.map(function(t){if(null===t||void 0===t)return t;if(!t.key)throw new Error("must set key for <rc-animate> children");return l["default"].createElement(p["default"],{key:t.key,ref:t.key,animation:e.animation,transitionName:e.transitionName,transitionEnter:e.transitionEnter,transitionAppear:e.transitionAppear,transitionLeave:e.transitionLeave},t)}));var r=e.component;if(r){var o=e;return"string"==typeof r&&(o={className:e.className,style:e.style}),l["default"].createElement(r,o,n)}return n[0]||null}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},i=n(1),a=r(i),s=n(4),l=r(s),u=n(77),c=r(u),p=n(136),f=r(p),d={enter:"transitionEnter",appear:"transitionAppear",leave:"transitionLeave"},h=a["default"].createClass({displayName:"AnimateChild",propTypes:{children:a["default"].PropTypes.any},componentWillUnmount:function(){this.stop()},componentWillEnter:function(e){f["default"].isEnterSupported(this.props)?this.transition("enter",e):e()},componentWillAppear:function(e){f["default"].isAppearSupported(this.props)?this.transition("appear",e):e()},componentWillLeave:function(e){f["default"].isLeaveSupported(this.props)?this.transition("leave",e):e()},transition:function(e,t){var n=this,r=l["default"].findDOMNode(this),i=this.props,a=i.transitionName,s="object"===("undefined"==typeof a?"undefined":o(a));this.stop();var p=function(){n.stopper=null,t()};if((u.isCssAnimationSupported||!i.animation[e])&&a&&i[d[e]]){var f=s?a[e]:a+"-"+e,h=f+"-active";s&&a[e+"Active"]&&(h=a[e+"Active"]),this.stopper=(0,c["default"])(r,{name:f,active:h},p)}else this.stopper=i.animation[e](r,p)},stop:function(){var e=this.stopper;e&&(this.stopper=null,e.stop())},render:function(){return this.props.children}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=[];return p["default"].Children.forEach(e,function(e){t.push(e)}),t}function i(e,t){var n=null;return e&&e.forEach(function(e){n||e&&e.key===t&&(n=e)}),n}function a(e,t,n){var r=null;return e&&e.forEach(function(e){if(e&&e.key===t&&e.props[n]){if(r)throw new Error("two child with same key for <rc-animate> children");r=e}}),r}function s(e,t,n){var r=0;return e&&e.forEach(function(e){r||(r=e&&e.key===t&&!e.props[n])}),r}function l(e,t,n){var r=e.length===t.length;return r&&e.forEach(function(e,o){var i=t[o];e&&i&&(e&&!i||!e&&i?r=!1:e.key!==i.key?r=!1:n&&e.props[n]!==i.props[n]&&(r=!1))}),r}function u(e,t){var n=[],r={},o=[];return e.forEach(function(e){e&&i(t,e.key)?o.length&&(r[e.key]=o,o=[]):o.push(e)}),t.forEach(function(e){e&&r.hasOwnProperty(e.key)&&(n=n.concat(r[e.key])),n.push(e)}),n=n.concat(o)}Object.defineProperty(t,"__esModule",{value:!0}),t.toArrayChildren=o,t.findChildInChildrenByKey=i,t.findShownChildInChildrenByKey=a,t.findHiddenChildInChildrenByKey=s,t.isSameChildren=l,t.mergeChildren=u;var c=n(1),p=r(c)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(){var e=this.state.value.clone();e.setDayOfMonth(1),this.setValue(e)}function a(){var e=this.state.value.clone();e.setDayOfMonth(e.getActualMaximum(h["default"].MONTH)),this.setValue(e)}function s(e){var t=this.state.value.clone();t.addMonth(e),this.setValue(t)}function l(e){var t=this.state.value.clone();t.addYear(e),this.setValue(t)}function u(e){var t=this.state.value.clone();t.addWeekOfYear(e),this.setValue(t)}function c(e){var t=this.state.value.clone();t.addDayOfMonth(e),this.setValue(t)}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(14),h=r(d),y=n(15),v=r(y),m=n(80),g=r(m),b=n(139),P=r(b),C=n(393),T=r(C),O=n(81),w=r(O),x=n(54),E=r(x),S=n(143),k=r(S),N=f["default"].createClass({displayName:"Calendar",propTypes:{disabledDate:p.PropTypes.func,disabledTime:p.PropTypes.any,value:p.PropTypes.object,selectedValue:p.PropTypes.object,defaultValue:p.PropTypes.object,className:p.PropTypes.string,locale:p.PropTypes.object,showWeekNumber:p.PropTypes.bool,style:p.PropTypes.object,showToday:p.PropTypes.bool,showDateInput:p.PropTypes.bool,visible:p.PropTypes.bool,onSelect:p.PropTypes.func,onOk:p.PropTypes.func,showOk:p.PropTypes.bool,prefixCls:p.PropTypes.string,onKeyDown:p.PropTypes.func,timePicker:p.PropTypes.element,dateInputPlaceholder:p.PropTypes.any,onClear:p.PropTypes.func,onChange:p.PropTypes.func},mixins:[E["default"],w["default"]],getDefaultProps:function(){return{showToday:!0,showDateInput:!0,timePicker:null,onOk:o}},onKeyDown:function(e){if("input"!==e.target.nodeName.toLowerCase()){var t=e.keyCode,n=e.ctrlKey||e.metaKey;switch(t){case v["default"].DOWN:return u.call(this,1),e.preventDefault(),1;case v["default"].UP:return u.call(this,-1),e.preventDefault(),1;case v["default"].LEFT:return n?l.call(this,-1):c.call(this,-1),e.preventDefault(),1;case v["default"].RIGHT:return n?l.call(this,1):c.call(this,1),e.preventDefault(),1;case v["default"].HOME:return i.call(this),e.preventDefault(),1;case v["default"].END:return a.call(this),e.preventDefault(),1;case v["default"].PAGE_DOWN:return s.call(this,1),e.preventDefault(),1;case v["default"].PAGE_UP:return s.call(this,-1),e.preventDefault(),1;case v["default"].ENTER:return this.onSelect(this.state.value,{source:"keyboard"}),e.preventDefault(),1;default:return this.props.onKeyDown(e),1}}},onClear:function(){this.onSelect(null),this.props.onClear()},onOk:function(){var e=this.state.selectedValue;this.isAllowedDate(e)&&this.props.onOk(e)},onDateInputChange:function(e){this.onSelect(e,{source:"dateInput"})},onDateTableSelect:function(e){this.onSelect(e)},chooseToday:function(){var e=this.state.value.clone();e.setTime(Date.now()),this.onSelect(e,{source:"todayButton"})},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.disabledDate,o=e.dateInputPlaceholder,i=e.timePicker,a=e.disabledTime,s=this.state,l=s.value,u=s.selectedValue,c=e.showDateInput?f["default"].createElement(k["default"],{ref:"dateInput",formatter:this.getFormatter(),key:"date-input",timePicker:i,gregorianCalendarLocale:l.locale,locale:t,placeholder:o,showClear:!0,disabledTime:a,disabledDate:r,onClear:this.onClear,prefixCls:n,selectedValue:u,onChange:this.onDateInputChange}):null,p=[c,f["default"].createElement("div",{key:"date-panel",className:n+"-date-panel"},f["default"].createElement(P["default"],{locale:t,onValueChange:this.setValue,value:l,prefixCls:n}),f["default"].createElement("div",{className:n+"-calendar-body"},f["default"].createElement(g["default"],{locale:t,value:l,selectedValue:u,prefixCls:n,dateRender:e.dateRender,onSelect:this.onDateTableSelect,disabledDate:r,showWeekNumber:e.showWeekNumber})),f["default"].createElement(T["default"],{showOk:e.showOk,locale:t,prefixCls:n,showToday:e.showToday,disabledTime:a,gregorianCalendarLocale:l.locale,showDateInput:e.showDateInput,timePicker:i,selectedValue:u,value:l,disabledDate:r,onOk:this.onOk,onSelect:this.onSelect,onToday:this.chooseToday}))];return this.renderRoot({children:p,className:e.showWeekNumber?n+"-week-number":""})}});t["default"]=N,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(80),l=r(s),u=n(147),c=r(u),p=n(81),f=r(p),d=n(54),h=r(d),y=n(397),v=r(y),m=a["default"].createClass({displayName:"FullCalendar",propTypes:{defaultType:i.PropTypes.string,type:i.PropTypes.string,prefixCls:i.PropTypes.string,locale:i.PropTypes.object,onTypeChange:i.PropTypes.func,fullscreen:i.PropTypes.bool,monthCellRender:i.PropTypes.func,dateCellRender:i.PropTypes.func,showTypeSwitch:i.PropTypes.bool,Select:i.PropTypes.func.isRequired,headerComponents:i.PropTypes.array,headerComponent:i.PropTypes.object,headerRender:i.PropTypes.func,showHeader:i.PropTypes.bool},mixins:[h["default"],f["default"]],getDefaultProps:function(){return{defaultType:"date",fullscreen:!1,showTypeSwitch:!0,showHeader:!0,onTypeChange:function(){}}},getInitialState:function(){var e=void 0;return e="type"in this.props?this.props.type:this.props.defaultType,{type:e}},componentWillReceiveProps:function(e){"type"in e&&this.setState({type:e.type})},onMonthSelect:function(e){this.onSelect(e,{target:"month"})},setType:function(e){"type"in this.props||this.setState({type:e}),this.props.onTypeChange(e)},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.fullscreen,i=e.showHeader,s=e.headerComponent,u=e.headerRender,p=this.state,f=p.value,d=p.type,h=null;if(i)if(u)h=u(f,d,t);else{var y=s||v["default"];h=a["default"].createElement(y,o({key:"calendar-header"},e,{prefixCls:n+"-full",type:d,value:f,onTypeChange:this.setType,onValueChange:this.setValue}))}var m="date"===d?a["default"].createElement(l["default"],{dateRender:e.dateCellRender,contentRender:e.dateCellContentRender,locale:t,prefixCls:n,onSelect:this.onSelect,value:f}):a["default"].createElement(c["default"],{cellRender:e.monthCellRender,contentRender:e.monthCellContentRender,locale:t,onSelect:this.onMonthSelect,prefixCls:n+"-month-panel",value:f}),g=[h,a["default"].createElement("div",{key:"calendar-body",className:n+"-calendar-body"},m)],b=[n+"-full"];return r&&b.push(n+"-fullscreen"),this.renderRoot({children:g,className:b.join(" ")})}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(){}function a(){var e=new y["default"];return e.setTime(Date.now()),e}function s(e,t){var n=void 0;n=t,"right"===e&&n.addMonth(-1),this.fireValueChange(n)}function l(e,t){var n=e.selectedValue||t&&e.defaultSelectedValue||[],r=e.value;Array.isArray(r)&&(r=r[0]);var o=e.defaultValue;return Array.isArray(o)&&(o=o[0]),r||t&&o||n[0]||t&&a()}function u(e,t){if(t){var n=this.state.selectedValue,r=n.concat(),o="left"===e?0:1;r[o]=t,r[0]&&r[1]&&this.compare(r[0],r[1])>0&&(r[1-o]=void 0),this.fireSelectValueChange(r)}}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=function(){function e(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,s=e[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(l){o=!0,i=l}finally{try{!r&&s["return"]&&s["return"]()}finally{if(o)throw i}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),f=n(1),d=r(f),h=n(14),y=r(h),v=n(2),m=r(v),g=n(400),b=r(g),P=n(19),C=n(141),T=r(C),O=n(140),w=r(O),x=n(54),E=r(x),S=d["default"].createClass({displayName:"RangeCalendar",propTypes:{prefixCls:f.PropTypes.string,dateInputPlaceholder:f.PropTypes.any,defaultValue:f.PropTypes.any,timePicker:f.PropTypes.any,value:f.PropTypes.any,showOk:f.PropTypes.bool,selectedValue:f.PropTypes.array,defaultSelectedValue:f.PropTypes.array,onOk:f.PropTypes.func,locale:f.PropTypes.object,onChange:f.PropTypes.func,onSelect:f.PropTypes.func,onValueChange:f.PropTypes.func,formatter:f.PropTypes.oneOfType([f.PropTypes.object,f.PropTypes.string]),onClear:f.PropTypes.func},mixins:[E["default"]],getDefaultProps:function(){return{defaultSelectedValue:[],onValueChange:i}},getInitialState:function(){var e=this.props,t=e.selectedValue||e.defaultSelectedValue,n=l(e,1);return{selectedValue:t,value:n}},componentWillReceiveProps:function(e){var t={};"value"in e&&(e.value?t.value=e.value:t.value=l(e,0),this.setState(t)),"selectedValue"in e&&(t.selectedValue=e.selectedValue,this.setState(t))},onSelect:function(e){var t=this.state.selectedValue,n=t.concat(),r=!1;!n.length||2===n.length&&!t.hovering?(n.length=1,n[0]=e,r=!0):this.compare(n[0],e)<=0?(n[1]=e,r=!0):this.compare(n[0],e)>0&&(n.length=1,n[0]=e,r=!0),r&&this.fireSelectValueChange(n)},onDayHover:function(e){var t=this.state.selectedValue;t.length&&(2!==t.length||t.hovering)&&(this.compare(e,t[0])<0||(t=t.concat(),t[1]=e,t.hovering=1,this.fireSelectValueChange(t)))},onToday:function(){this.setState({value:(0,P.getTodayTime)(this.state.value)})},onOk:function(){this.props.onOk(this.state.selectedValue)},getStartValue:function(){var e=this.state.value,t=this.state.selectedValue;return t[0]&&this.props.timePicker&&(e=e.clone(),(0,P.syncTime)(t[0],e)),e},getEndValue:function(){var e=this.state.value.clone();e.addMonth(1);var t=this.state.selectedValue;return t[1]&&this.props.timePicker&&(0,P.syncTime)(t[1],e),e},compare:function(e,t){return this.props.timePicker?e.getTime()-t.getTime():e.compareToDay(t)},fireSelectValueChange:function(e,t){"selectedValue"in this.props||this.setState({selectedValue:e}),this.props.onChange(e),(t||e[0]&&e[1]&&!e.hovering)&&this.props.onSelect(e)},fireValueChange:function(e){var t=this.props;"value"in t||this.setState({value:e}),t.onValueChange(e)},clear:function(){this.fireSelectValueChange([],!0),this.props.onClear()},render:function(){var e,t=this.props,n=this.state,r=t.prefixCls,i=t.dateInputPlaceholder,a=t.timePicker,l=t.showOk,f=t.locale,h=(e={},o(e,t.className,!!t.className),o(e,r,1),o(e,r+"-hidden",!t.visible),o(e,r+"-range",1),o(e,r+"-week-number",t.showWeekNumber),e),y=(0,m["default"])(h),v={selectedValue:n.selectedValue,onSelect:this.onSelect,onDayHover:this.onDayHover},g=void 0,P=void 0;if(i)if(Array.isArray(i)){var C=p(i,2);g=C[0],P=C[1]}else g=P=i;return d["default"].createElement("div",{ref:"root",className:y,style:t.style,tabIndex:"0"},d["default"].createElement("a",{className:r+"-clear-btn",role:"button",title:f.clear,onClick:this.clear}),d["default"].createElement(b["default"],c({},t,v,{direction:"left",formatter:this.getFormatter(),value:this.getStartValue(),placeholder:g,onInputSelect:u.bind(this,"left"),onValueChange:s.bind(this,"left")})),d["default"].createElement("span",{className:r+"-range-middle"},"~"),d["default"].createElement(b["default"],c({},t,v,{direction:"right",formatter:this.getFormatter(),placeholder:P,value:this.getEndValue(),onInputSelect:u.bind(this,"right"),onValueChange:s.bind(this,"right")})),d["default"].createElement("div",{className:r+"-range-bottom"},d["default"].createElement(T["default"],c({},t,{value:n.value,onToday:this.onToday,text:f.backToToday})),l===!0||l!==!1&&a?d["default"].createElement(w["default"],c({},t,{value:n.value,onOk:this.onOk,okDisabled:2!==n.selectedValue.length||n.selectedValue.hovering})):null))}});t["default"]=S,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(4),l=r(s),u=n(170),c=r(u),p=n(141),f=r(p),d=n(140),h=r(d),y=n(19),v=a["default"].createClass({displayName:"CalendarFooter",propTypes:{prefixCls:i.PropTypes.string,showDateInput:i.PropTypes.bool,disabledTime:i.PropTypes.any,gregorianCalendarLocale:i.PropTypes.object,selectedValue:i.PropTypes.any,showOk:i.PropTypes.bool,onSelect:i.PropTypes.func,value:i.PropTypes.object,defaultValue:i.PropTypes.object},onSelect:function(e){this.props.onSelect(e)},getRootDOMNode:function(){return l["default"].findDOMNode(this)},render:function(){var e=this.props,t=e.value,n=e.prefixCls,r=e.showDateInput,i=e.disabledTime,s=e.gregorianCalendarLocale,l=e.selectedValue,u=e.showOk,p=!r&&e.timePicker||null,d=i&&p?(0,y.getTimeConfig)(l,i):null,v=null;if(e.showToday||p){var m=void 0;e.showToday&&(m=a["default"].createElement(f["default"],o({},e,{value:t})));var g=void 0;(u===!0||u!==!1&&e.timePicker)&&(g=a["default"].createElement(h["default"],e));var b=void 0;(m||g)&&(b=a["default"].createElement("span",{className:n+"-footer-btn"},(0,c["default"])([m,g]))),p&&(p=a["default"].cloneElement(p,o({onChange:this.onSelect,allowEmpty:!1,gregorianCalendarLocale:s},d,{getPopupContainer:this.getRootDOMNode,value:l}))),v=a["default"].createElement("div",{className:n+"-footer"},p,b)}return v}});t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return e&&t&&0===e.compareToDay(t)}function i(e,t){return e.getYear()<t.getYear()?1:e.getYear()===t.getYear()&&e.getMonth()<t.getMonth()}function a(e,t){return e.getYear()>t.getYear()?1:e.getYear()===t.getYear()&&e.getMonth()>t.getMonth()}function s(e){return"rc-calendar-"+e.getYear()+"-"+e.getMonth()+"-"+e.getDayOfMonth()}function l(){}function u(e){this.props.onSelect(e)}function c(e){this.props.onDayHover(e)}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(142),h=r(d),y=n(19),v=f["default"].createClass({displayName:"DateTBody",propTypes:{contentRender:p.PropTypes.func,dateRender:p.PropTypes.func,disabledDate:p.PropTypes.func,prefixCls:p.PropTypes.string,selectedValue:p.PropTypes.oneOfType([p.PropTypes.object,p.PropTypes.arrayOf(p.PropTypes.object)]),value:p.PropTypes.object,showWeekNumber:p.PropTypes.bool },getDefaultProps:function(){return{onDayHover:l}},render:function(){var e=this.props,t=e.contentRender,n=e.prefixCls,r=e.selectedValue,p=e.value,d=e.showWeekNumber,v=e.dateRender,m=e.disabledDate,g=void 0,b=void 0,P=void 0,C=[],T=p.clone(),O=n+"-cell",w=n+"-week-number-cell",x=n+"-date",E=n+"-today",S=n+"-selected-day",k=n+"-in-range-cell",N=n+"-last-month-cell",j=n+"-next-month-btn-day",_=n+"-disabled-cell",M=n+"-disabled-cell-first-of-row",D=n+"-disabled-cell-last-of-row";T.setTime(Date.now());var A=p.clone();A.set(p.getYear(),p.getMonth(),1);var L=A.getDayOfWeek(),V=(L+7-p.getFirstDayOfWeek())%7,I=A.clone();I.addDayOfMonth(0-V);var F=0;for(g=0;g<h["default"].DATE_ROW_COUNT;g++)for(b=0;b<h["default"].DATE_COL_COUNT;b++)P=I,F&&(P=P.clone(),P.addDayOfMonth(F)),C.push(P),F++;var R=[];for(F=0,g=0;g<h["default"].DATE_ROW_COUNT;g++){var K=void 0,W=[];for(d&&(K=f["default"].createElement("td",{key:C[F].getWeekOfYear(),role:"gridcell",className:w},C[F].getWeekOfYear())),b=0;b<h["default"].DATE_COL_COUNT;b++){var H=null,z=null;P=C[F],b<h["default"].DATE_COL_COUNT-1&&(H=C[F+1]),b>0&&(z=C[F-1]);var U=O,B=!1,Y=!1;o(P,T)&&(U+=" "+E);var q=i(P,p),X=a(P,p);if(r&&Array.isArray(r)){if(!q&&!X){var G=r[0],$=r[1];G&&o(P,G)&&(Y=!0),G&&$&&(o(P,$)&&!r.hovering?Y=!0:P.compareToDay(G)>0&&P.compareToDay($)<0&&(U+=" "+k))}}else o(P,p)&&(Y=!0);q&&(U+=" "+N),X&&(U+=" "+j),m&&m(P,p)&&(B=!0,z&&m(z,p)||(U+=" "+M),H&&m(H,p)||(U+=" "+D)),Y&&(U+=" "+S),B&&(U+=" "+_);var Q=void 0;if(v)Q=v(P,p);else{var Z=t?t(P,p):P.getDayOfMonth();Q=f["default"].createElement("div",{key:s(P),className:x,"aria-selected":Y,"aria-disabled":B},Z)}W.push(f["default"].createElement("td",{key:F,onClick:B?l:u.bind(this,P),onMouseEnter:B?l:c.bind(this,P),role:"gridcell",title:(0,y.getTitleString)(P),className:U},Q)),F++}R.push(f["default"].createElement("tr",{key:g,role:"row"},K,W))}return f["default"].createElement("tbody",{className:n+"tbody"},R)}});t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=n(142),p=r(c),f=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){for(var e=this.props,t=e.value,n=e.locale,r=e.prefixCls,o=[],i=[],a=t.getFirstDayOfWeek(),s=void 0,l=0;l<p["default"].DATE_COL_COUNT;l++){var c=(a+l)%p["default"].DATE_COL_COUNT;o[l]=n.format.veryShortWeekdays[c],i[l]=n.format.weekdays[c]}e.showWeekNumber&&(s=u["default"].createElement("th",{role:"columnheader",className:r+"-column-header "+r+"-week-number-header"},u["default"].createElement("span",{className:r+"-column-header-inner"},"x")));var f=i.map(function(e,t){return u["default"].createElement("th",{key:t,role:"columnheader",title:e,className:r+"-column-header"},u["default"].createElement("span",{className:r+"-column-header-inner"},o[t]))});return u["default"].createElement("thead",null,u["default"].createElement("tr",{role:"row"},s,f))},t}(u["default"].Component);t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}function u(e){var t=this.state.value.clone();t.addYear(e),this.setState({value:t})}function c(e,t){var n=this.state.value.clone();n.setYear(e),n.rollSetMonth(this.state.value.getMonth()),this.props.onSelect(n),t.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(2),h=r(d),y=4,v=3,m=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return r.state={value:n.value||n.defaultValue},r.prefixCls=n.rootPrefixCls+"-decade-panel",r.nextCentury=u.bind(r,100),r.previousCentury=u.bind(r,-100),r}return l(t,e),t.prototype.render=function(){for(var e=this,t=this.state.value,n=this.props.locale,r=t.getYear(),o=100*parseInt(r/100,10),a=o-10,s=o+99,l=[],u=0,p=this.prefixCls,d=0;d<y;d++){l[d]=[];for(var m=0;m<v;m++){var g=a+10*u,b=a+10*u+9;l[d][m]={startDecade:g,endDecade:b},u++}}var P=l.map(function(t,n){var a=t.map(function(t){var n,a=t.startDecade,l=t.endDecade,u=a<o,d=l>s,y=(n={},i(n,p+"-cell",1),i(n,p+"-selected-cell",a<=r&&r<=l),i(n,p+"-last-century-cell",u),i(n,p+"-next-century-cell",d),n),v=void 0,m=void 0;return u?m=e.previousCentury:d?m=e.nextCentury:(v=a+"-"+l,m=c.bind(e,a)),f["default"].createElement("td",{key:a,onClick:m,role:"gridcell",className:(0,h["default"])(y)},f["default"].createElement("a",{className:p+"-decade"},v))});return f["default"].createElement("tr",{key:n,role:"row"},a)});return f["default"].createElement("div",{className:this.prefixCls},f["default"].createElement("div",{className:p+"-header"},f["default"].createElement("a",{className:p+"-prev-century-btn",role:"button",onClick:this.previousCentury,title:n.previousCentury},"\xab"),f["default"].createElement("div",{className:p+"-century"},o,"-",s),f["default"].createElement("a",{className:p+"-next-century-btn",role:"button",onClick:this.nextCentury,title:n.nextCentury},"\xbb")),f["default"].createElement("div",{className:p+"-body"},f["default"].createElement("table",{className:p+"-table",cellSpacing:"0",role:"grid"},f["default"].createElement("tbody",{className:p+"-tbody"},P))))},t}(f["default"].Component);t["default"]=m,m.propTypes={locale:p.PropTypes.object,value:p.PropTypes.object,defaultValue:p.PropTypes.object,rootPrefixCls:p.PropTypes.string},m.defaultProps={onSelect:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0});var u=n(1),c=r(u),p=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.onYearChange=function(e){var t=this.props.value.clone();t.setYear(parseInt(e,10)),this.props.onValueChange(t)},t.prototype.onMonthChange=function(e){var t=this.props.value.clone();t.setMonth(parseInt(e,10)),this.props.onValueChange(t)},t.prototype.getYearSelectElement=function(e){for(var t=this.props,n=t.yearSelectOffset,r=t.yearSelectTotal,o=t.locale,i=t.prefixCls,a=t.Select,s=e-n,l=s+r,u="\u5e74"===o.year?"\u5e74":"",p=[],f=s;f<l;f++)p.push(c["default"].createElement(a.Option,{key:""+f},f+u));return c["default"].createElement(a,{className:i+"-header-year-select",onChange:this.onYearChange.bind(this),dropdownStyle:{zIndex:2e3},dropdownMenuStyle:{maxHeight:250,overflow:"auto",fontSize:12},optionLabelProp:"children",value:String(e),showSearch:!1},p)},t.prototype.getMonthSelectElement=function(e){for(var t=this.props,n=t.locale.format.months,r=t.prefixCls,o=[],i=t.Select,a=0;a<12;a++)o.push(c["default"].createElement(i.Option,{key:""+a},n[a]));return c["default"].createElement(i,{className:r+"-header-month-select",dropdownStyle:{zIndex:2e3},dropdownMenuStyle:{maxHeight:250,overflow:"auto",overflowX:"hidden",fontSize:12},optionLabelProp:"children",value:String(e),showSearch:!1,onChange:this.onMonthChange.bind(this)},o)},t.prototype.changeTypeToDate=function(){this.props.onTypeChange("date")},t.prototype.changeTypeToMonth=function(){this.props.onTypeChange("month")},t.prototype.render=function(){var e=this.props,t=e.value,n=e.locale,r=e.prefixCls,o=e.type,i=e.showTypeSwitch,a=e.headerComponents,s=t.getYear(),l=t.getMonth(),u=this.getYearSelectElement(s),p="month"===o?null:this.getMonthSelectElement(l),f=r+"-header-switcher",d=i?c["default"].createElement("span",{className:f},"date"===o?c["default"].createElement("span",{className:f+"-focus"},n.month):c["default"].createElement("span",{onClick:this.changeTypeToDate.bind(this),className:f+"-normal"},n.month),"month"===o?c["default"].createElement("span",{className:f+"-focus"},n.year):c["default"].createElement("span",{onClick:this.changeTypeToMonth.bind(this),className:f+"-normal"},n.year)):null;return c["default"].createElement("div",{className:r+"-header"},d,p,u,a)},t}(u.Component);p.propTypes={value:u.PropTypes.object,locale:u.PropTypes.object,yearSelectOffset:u.PropTypes.number,yearSelectTotal:u.PropTypes.number,onValueChange:u.PropTypes.func,onTypeChange:u.PropTypes.func,Select:u.PropTypes.func,prefixCls:u.PropTypes.string,type:u.PropTypes.string,showTypeSwitch:u.PropTypes.bool,headerComponents:u.PropTypes.array},p.defaultProps={yearSelectOffset:10,yearSelectTotal:20,onValueChange:l,onTypeChange:l},t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(79),i=r(o);t["default"]={today:"Today",now:"Now",backToToday:"Back to today",ok:"Ok",clear:"Clear",month:"Month",year:"Year",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",yearFormat:"yyyy",dateFormat:"M/d/yyyy",monthFormat:"MMMM",monthBeforeYear:!0,previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century",format:i["default"]},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o={bottomLeft:{points:["tl","tl"],overflow:n,offset:[0,-3],targetOffset:r},bottomRight:{points:["tr","tr"],overflow:n,offset:[0,-3],targetOffset:r},topRight:{points:["br","br"],overflow:n,offset:[0,3],targetOffset:r},topLeft:{points:["bl","bl"],overflow:n,offset:[0,3],targetOffset:r}};t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(139),l=r(s),u=n(80),c=r(u),p=n(143),f=r(p),d=a["default"].createClass({displayName:"CalendarPart",propTypes:{value:i.PropTypes.any,direction:i.PropTypes.any,prefixCls:i.PropTypes.any,locale:i.PropTypes.any,selectedValue:i.PropTypes.any,formatter:i.PropTypes.any,placeholder:i.PropTypes.any,disabledDate:i.PropTypes.any,timePicker:i.PropTypes.any,disabledTime:i.PropTypes.any},render:function(){var e=this.props,t=e.value,n=e.direction,r=e.prefixCls,i=e.locale,s=e.selectedValue,u=e.formatter,p=e.placeholder,d=e.disabledDate,h=e.timePicker,y=e.disabledTime,v=r+"-range",m={locale:i,value:t,prefixCls:r},g="left"===n?0:1;return a["default"].createElement("div",{className:v+"-part "+v+"-"+n},a["default"].createElement(f["default"],{formatter:u,locale:i,prefixCls:r,timePicker:h,disabledDate:d,placeholder:p,disabledTime:y,gregorianCalendarLocale:t.locale,showClear:!1,selectedValue:s[g],onChange:e.onInputSelect}),a["default"].createElement("div",{style:{outline:"none"}},a["default"].createElement(l["default"],o({},m,{enableNext:"right"===n,enablePrev:"left"===n,onValueChange:e.onValueChange})),a["default"].createElement("div",{className:r+"-calendar-body"},a["default"].createElement(c["default"],o({},m,{selectedValue:s,dateRender:e.dateRender,onSelect:e.onSelect,onDayHover:e.onDayHover,disabledDate:d,showWeekNumber:e.showWeekNumber})))))}});t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=n(1),p=r(c),f=n(28),d=r(f),h=n(402),y=r(h),v={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:1,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:1,adjustY:1}},bottomRight:{points:["tr","br"],offset:[0,4],overflow:{adjustX:1,adjustY:1}},topRight:{points:["br","tr"],offset:[0,-4],overflow:{adjustX:1,adjustY:1}}},m=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));r.setPopupVisible=function(e){"popupVisible"in r.props||r.setState({popupVisible:e}),e&&!r.state.visible&&r.setState({activeValue:r.state.value}),r.props.onPopupVisibleChange(e)},r.handleChange=function(e,t){r.props.onChange(e.map(function(e){return e.value}),e),r.setPopupVisible(t.visible)},r.handlePopupVisibleChange=function(e){r.setPopupVisible(e)},r.handleSelect=function(e){var t=i(e,[]);"value"in r.props&&delete t.value,r.setState(t)};var o=[];return"value"in n?o=n.value||[]:"defaultValue"in n&&(o=n.defaultValue||[]),r.state={popupVisible:n.popupVisible,activeValue:o,value:o},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){if("value"in e&&this.props.value!==e.value){var t={value:e.value||[],activeValue:e.value||[]};"loadData"in e&&delete t.activeValue,this.setState(t)}"popupVisible"in e&&this.setState({popupVisible:e.popupVisible})},t.prototype.getPopupDOMNode=function(){return this.refs.trigger.getPopupDomNode()},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.transitionName,r=e.popupClassName,o=e.popupPlacement,a=i(e,["prefixCls","transitionName","popupClassName","popupPlacement"]),s=p["default"].createElement("div",null),l="";return e.options&&e.options.length>0?s=p["default"].createElement(y["default"],u({},e,{value:this.state.value,activeValue:this.state.activeValue,onSelect:this.handleSelect,onChange:this.handleChange,visible:this.state.popupVisible})):l=" "+t+"-menus-empty",p["default"].createElement(d["default"],u({ref:"trigger"},a,{popupPlacement:o,builtinPlacements:v,popupTransitionName:n,action:e.disabled?[]:["click"],popupVisible:!e.disabled&&this.state.popupVisible,onPopupVisibleChange:this.handlePopupVisibleChange,prefixCls:t+"-menus",popupClassName:r+l,popup:s}),e.children)},t}(p["default"].Component);m.defaultProps={options:[],onChange:function(){},onPopupVisibleChange:function(){},disabled:!1,transitionName:"",prefixCls:"rc-cascader",popupClassName:"",popupPlacement:"bottomLeft"},m.propTypes={value:p["default"].PropTypes.array,defaultValue:p["default"].PropTypes.array,options:p["default"].PropTypes.array.isRequired,onChange:p["default"].PropTypes.func,onPopupVisibleChange:p["default"].PropTypes.func,popupVisible:p["default"].PropTypes.bool,disabled:p["default"].PropTypes.bool,transitionName:p["default"].PropTypes.string,popupClassName:p["default"].PropTypes.string,popupPlacement:p["default"].PropTypes.string,prefixCls:p["default"].PropTypes.string,dropdownMenuColumnStyle:p["default"].PropTypes.object},t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(1),c=r(u),p=n(86),f=r(p),d=n(4),h=function(e){function t(){return i(this,t),a(this,e.apply(this,arguments))}return s(t,e),t.prototype.componentDidMount=function(){this.scrollActiveItemToView()},t.prototype.componentDidUpdate=function(e){!e.visible&&this.props.visible&&this.scrollActiveItemToView()},t.prototype.onSelect=function(e,t){if(e&&!e.disabled){var n=this.props.activeValue;n=n.slice(0,t+1),n[t]=e.value;var r=this.getActiveOptions(n);if(e.isLeaf===!1&&!e.children&&this.props.loadData)return this.props.changeOnSelect&&this.props.onChange(r,{visible:!0}),this.props.onSelect({activeValue:n}),void this.props.loadData(r);var o={};e.children&&e.children.length?this.props.changeOnSelect&&(this.props.onChange(r,{visible:!0}),o.value=n):(this.props.onChange(r,{visible:!1}),o.value=n),o.activeValue=n,this.props.onSelect(o)}},t.prototype.getOption=function(e,t){var n=this.props,r=n.prefixCls,o=n.expandTrigger,i=this.onSelect.bind(this,e,t),a={onClick:i},s=r+"-menu-item",u=e.children&&e.children.length>0;(u||e.isLeaf===!1)&&(s+=" "+r+"-menu-item-expand"),"hover"===o&&u&&(a={onMouseEnter:this.delayOnSelect.bind(this,i),onMouseLeave:this.delayOnSelect.bind(this)}),this.isActiveOption(e)&&(s+=" "+r+"-menu-item-active",a.ref="activeItem"+t),e.disabled&&(s+=" "+r+"-menu-item-disabled"),e.loading&&(s+=" "+r+"-menu-item-loading");var p="";return e.title?p=e.title:"string"==typeof e.label&&(p=e.label),c["default"].createElement("li",l({key:e.value,className:s,title:p},a),e.label)},t.prototype.getActiveOptions=function(e){var t=e||this.props.activeValue,n=this.props.options;return(0,f["default"])(n,function(e,n){return e.value===t[n]})},t.prototype.getShowOptions=function(){var e=this.props.options,t=this.getActiveOptions().map(function(e){return e.children}).filter(function(e){return!!e});return t.unshift(e),t},t.prototype.delayOnSelect=function(e){var t=this;this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),"function"==typeof e&&(this.delayTimer=setTimeout(function(){e(),t.delayTimer=null},150))},t.prototype.scrollActiveItemToView=function(){for(var e=this.getShowOptions().length,t=0;t<e;t++){var n=this.refs["activeItem"+t];if(n){var r=(0,d.findDOMNode)(n);r.parentNode.scrollTop=r.offsetTop}}},t.prototype.isActiveOption=function(e){return this.props.activeValue.some(function(t){return t===e.value})},t.prototype.render=function(){var e=this,t=this.props,n=t.prefixCls,r=t.dropdownMenuColumnStyle;return c["default"].createElement("div",null,this.getShowOptions().map(function(t,o){return c["default"].createElement("ul",{className:n+"-menu",key:o,style:r},t.map(function(t){return e.getOption(t,o)}))}))},t}(c["default"].Component);h.defaultProps={options:[],value:[],activeValue:[],onChange:function(){},onSelect:function(){},prefixCls:"rc-cascader-menus",visible:!1,expandTrigger:"click",changeOnSelect:!1},h.propTypes={value:c["default"].PropTypes.array,activeValue:c["default"].PropTypes.array,options:c["default"].PropTypes.array.isRequired,prefixCls:c["default"].PropTypes.string,expandTrigger:c["default"].PropTypes.string,onChange:c["default"].PropTypes.func,onSelect:c["default"].PropTypes.func,loadData:c["default"].PropTypes.func,visible:c["default"].PropTypes.bool,changeOnSelect:c["default"].PropTypes.bool,dropdownMenuColumnStyle:c["default"].PropTypes.object},t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(401),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=n(1),p=r(c),f=n(21),d=r(f),h=n(2),y=r(h),v=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));r.handleFocus=function(e){r.setState({focus:!0}),r.props.onFocus(e)},r.handleBlur=function(e){r.setState({focus:!1}),r.props.onBlur(e)},r.handleChange=function(e){"checked"in r.props||r.setState({checked:e.target.checked}),r.props.onChange({target:u({},r.props,{checked:e.target.checked}),stopPropagation:function(){e.stopPropagation()},preventDefault:function(){e.preventDefault()}})};var o=!1;return o="checked"in n?n.checked:n.defaultChecked,r.state={checked:o,focus:!1},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"checked"in e&&this.setState({checked:e.checked})},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return d["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=u({},this.props);delete t.defaultChecked;var n=this.state,r=t.prefixCls,o=n.checked;"boolean"==typeof o&&(o=o?1:0);var a=(0,y["default"])((e={},i(e,t.className,!!t.className),i(e,r,1),i(e,r+"-checked",o),i(e,r+"-checked-"+o,!!o),i(e,r+"-focused",n.focus),i(e,r+"-disabled",t.disabled),e));return p["default"].createElement("span",{className:a,style:t.style},p["default"].createElement("span",{className:r+"-inner"}),p["default"].createElement("input",{name:t.name,type:t.type,readOnly:t.readOnly,disabled:t.disabled,tabIndex:t.tabIndex,className:r+"-input",checked:!!o,onClick:this.props.onClick,onFocus:this.handleFocus,onBlur:this.handleBlur,onChange:this.handleChange}))},t}(p["default"].Component);v.propTypes={name:p["default"].PropTypes.string,prefixCls:p["default"].PropTypes.string,style:p["default"].PropTypes.object,type:p["default"].PropTypes.string,className:p["default"].PropTypes.string,defaultChecked:p["default"].PropTypes.oneOfType([p["default"].PropTypes.number,p["default"].PropTypes.bool]),checked:p["default"].PropTypes.oneOfType([p["default"].PropTypes.number,p["default"].PropTypes.bool]),onFocus:p["default"].PropTypes.func,onBlur:p["default"].PropTypes.func,onChange:p["default"].PropTypes.func,onClick:p["default"].PropTypes.func},v.defaultProps={prefixCls:"rc-checkbox",style:{},type:"checkbox",className:"",defaultChecked:!1,onFocus:function(){},onBlur:function(){},onChange:function(){}},t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function i(e){var t=e;return Array.isArray(t)||(t=t?[t]:[]),t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a),l=n(406),u=r(l),c=n(409),p=r(c),f=s["default"].createClass({displayName:"Collapse",propTypes:{children:a.PropTypes.any,prefixCls:a.PropTypes.string,activeKey:a.PropTypes.oneOfType([a.PropTypes.string,a.PropTypes.arrayOf(a.PropTypes.string)]),defaultActiveKey:a.PropTypes.oneOfType([a.PropTypes.string,a.PropTypes.arrayOf(a.PropTypes.string)]),openAnimation:a.PropTypes.object,onChange:a.PropTypes.func,accordion:a.PropTypes.bool},statics:{Panel:u["default"]},getDefaultProps:function(){return{prefixCls:"rc-collapse",onChange:function(){},accordion:!1}},getInitialState:function(){var e=this.props,t=e.activeKey,n=e.defaultActiveKey,r=n;return"activeKey"in this.props&&(r=t),{openAnimation:this.props.openAnimation||(0,p["default"])(this.props.prefixCls),activeKey:i(r)}},componentWillReceiveProps:function(e){"activeKey"in e&&this.setState({activeKey:i(e.activeKey)}),"openAnimation"in e&&this.setState({openAnimation:e.openAnimation})},onClickItem:function(e){var t=this;return function(){var n=t.state.activeKey;if(t.props.accordion)n=n[0]===e?[]:[e];else{n=[].concat(o(n));var r=n.indexOf(e),i=r>-1;i?n.splice(r,1):n.push(e)}t.setActiveKey(n)}},getItems:function(){var e=this,t=this.state.activeKey,n=this.props,r=n.prefixCls,o=n.accordion;return a.Children.map(this.props.children,function(n,i){var a=n.key||String(i),l=n.props.header,u=!1;u=o?t[0]===a:t.indexOf(a)>-1;var c={key:a,header:l,isActive:u,prefixCls:r,openAnimation:e.state.openAnimation,children:n.props.children,onItemClick:e.onClickItem(a).bind(e)};return s["default"].cloneElement(n,c)})},setActiveKey:function(e){"activeKey"in this.props||this.setState({activeKey:e}),this.props.onChange(this.props.accordion?e[0]:e)},render:function(){var e=this.props.prefixCls;return s["default"].createElement("div",{className:e},this.getItems())}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=n(2),l=r(s),u=n(407),c=r(u),p=n(9),f=r(p),d=a["default"].createClass({displayName:"CollapsePanel",propTypes:{className:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.object]),children:i.PropTypes.any,openAnimation:i.PropTypes.object,prefixCls:i.PropTypes.string,header:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.number,i.PropTypes.node]),isActive:i.PropTypes.bool,onItemClick:i.PropTypes.func},getDefaultProps:function(){return{isActive:!1,onItemClick:function(){}}},handleItemClick:function(){this.props.onItemClick()},render:function(){var e,t=this.props,n=t.className,r=t.prefixCls,i=t.header,s=t.children,u=t.isActive,p=r+"-header",d=(0,l["default"])((e={},o(e,r+"-item",!0),o(e,r+"-item-active",u),o(e,n,n),e));return a["default"].createElement("div",{className:d},a["default"].createElement("div",{className:p,onClick:this.handleItemClick,role:"tab","aria-expanded":u},a["default"].createElement("i",{className:"arrow"}),i),a["default"].createElement(f["default"],{showProp:"isActive",exclusive:!0,component:"",animation:this.props.openAnimation},a["default"].createElement(c["default"],{prefixCls:r,isActive:u},s)))}});t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=n(2),l=r(s),u=a["default"].createClass({displayName:"PanelContent",propTypes:{prefixCls:i.PropTypes.string,isActive:i.PropTypes.bool,children:i.PropTypes.any},shouldComponentUpdate:function(e){return this.props.isActive||e.isActive},render:function(){var e;if(this._isActived=this._isActived||this.props.isActive,!this._isActived)return null;var t=this.props,n=t.prefixCls,r=t.isActive,i=t.children,s=(0,l["default"])((e={},o(e,n+"-content",!0),o(e,n+"-content-active",r),o(e,n+"-content-inactive",!r),e));return a["default"].createElement("div",{className:s,role:"tabpanel"},a["default"].createElement("div",{className:n+"-content-box"},i))}});t["default"]=u,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(405),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r){var o=void 0;return(0,s["default"])(e,n,{start:function(){t?(o=e.offsetHeight,e.style.height=0):e.style.height=e.offsetHeight+"px"},active:function(){e.style.height=(t?o:0)+"px"},end:function(){e.style.height="",r()}})}function i(e){return{enter:function(t,n){return o(t,!0,e+"-anim",n)},leave:function(t,n){return o(t,!1,e+"-anim",n)}}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(77),s=r(a);t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function a(e,t){var n=e.style;["Webkit","Moz","Ms","ms"].forEach(function(e){n[e+"TransformOrigin"]=t}),n.transformOrigin=t}function s(e){var t=e.getBoundingClientRect(),n={left:t.left,top:t.top},r=e.ownerDocument,o=r.defaultView||r.parentWindow;return n.left+=i(o),n.top+=i(o,1),n}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]); }return e},u=n(1),c=r(u),p=n(4),f=r(p),d=n(15),h=r(d),y=n(9),v=r(y),m=n(412),g=r(m),b=0,P=0,C={position:"absolute",top:"-9999px",width:"50px",height:"50px",overflow:"scroll"},T=c["default"].createClass({displayName:"Dialog",propTypes:{onAfterClose:u.PropTypes.func,onClose:u.PropTypes.func,closable:u.PropTypes.bool,maskClosable:u.PropTypes.bool,visible:u.PropTypes.bool,mousePosition:u.PropTypes.object,wrapStyle:u.PropTypes.object,prefixCls:u.PropTypes.string,wrapClassName:u.PropTypes.string},getDefaultProps:function(){return{onAfterClose:o,onClose:o}},componentWillMount:function(){this.titleId="rcDialogTitle"+b++},componentDidMount:function(){this.componentDidUpdate({})},componentDidUpdate:function(e){var t=this.props,n=this.props.mousePosition;if(t.visible){if(!e.visible){this.lastOutSideFocusNode=document.activeElement,this.addScrollingEffect(),this.refs.wrap.focus();var r=f["default"].findDOMNode(this.refs.dialog);if(n){var o=s(r);a(r,n.x-o.left+"px "+(n.y-o.top)+"px")}else a(r,"")}}else if(e.visible&&t.mask&&this.lastOutSideFocusNode){try{this.lastOutSideFocusNode.focus()}catch(i){this.lastOutSideFocusNode=null}this.lastOutSideFocusNode=null}},onAnimateLeave:function(){this.refs.wrap&&(this.refs.wrap.style.display="none"),this.removeScrollingEffect(),this.props.onAfterClose()},onMaskClick:function(e){e.target===e.currentTarget&&this.props.closable&&this.props.maskClosable&&this.close(e)},onKeyDown:function(e){var t=this.props;if(t.closable&&t.keyboard&&e.keyCode===h["default"].ESC&&this.close(e),t.visible&&e.keyCode===h["default"].TAB){var n=document.activeElement,r=this.refs.wrap,o=this.refs.sentinel;e.shiftKey?n===r&&o.focus():n===this.refs.sentinel&&r.focus()}},getDialogElement:function(){var e=this.props,t=e.closable,n=e.prefixCls,r={};void 0!==e.width&&(r.width=e.width),void 0!==e.height&&(r.height=e.height);var o=void 0;e.footer&&(o=c["default"].createElement("div",{className:n+"-footer",ref:"footer"},e.footer));var i=void 0;e.title&&(i=c["default"].createElement("div",{className:n+"-header",ref:"header"},c["default"].createElement("div",{className:n+"-title",id:this.titleId},e.title)));var a=void 0;t&&(a=c["default"].createElement("button",{onClick:this.close,"aria-label":"Close",className:n+"-close"},c["default"].createElement("span",{className:n+"-close-x"})));var s=l({},e.style,r),u=this.getTransitionName(),p=c["default"].createElement(g["default"],{role:"document",ref:"dialog",style:s,className:n+" "+(e.className||""),visible:e.visible},c["default"].createElement("div",{className:n+"-content"},a,i,c["default"].createElement("div",{className:n+"-body",style:e.bodyStyle,ref:"body"},e.children),o),c["default"].createElement("div",{tabIndex:"0",ref:"sentinel",style:{width:0,height:0,overflow:"hidden"}},"sentinel"));return c["default"].createElement(v["default"],{key:"dialog",showProp:"visible",onLeave:this.onAnimateLeave,transitionName:u,component:"",transitionAppear:!0},p)},getZIndexStyle:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getWrapStyle:function(){return l({},this.getZIndexStyle(),this.props.wrapStyle)},getMaskElement:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=c["default"].createElement(g["default"],{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=c["default"].createElement(v["default"],{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},getMaskTransitionName:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getTransitionName:function(){var e=this.props,t=e.transitionName,n=e.animation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getElement:function(e){return this.refs[e]},setScrollbar:function(){this.bodyIsOverflowing&&this.scrollbarWidth&&(document.body.style.paddingRight=this.scrollbarWidth+"px")},addScrollingEffect:function(){P++,1===P&&(this.checkScrollbar(),this.setScrollbar(),document.body.style.overflow="hidden")},removeScrollingEffect:function(){P--,0===P&&(document.body.style.overflow="",this.resetScrollbar())},close:function(e){this.props.onClose(e)},checkScrollbar:function(){var e=window.innerWidth;if(!e){var t=document.documentElement.getBoundingClientRect();e=t.right-Math.abs(t.left)}this.bodyIsOverflowing=document.body.clientWidth<e,this.bodyIsOverflowing&&(this.scrollbarWidth=this.measureScrollbar())},resetScrollbar:function(){document.body.style.paddingRight=""},measureScrollbar:function(){if(void 0!==this.scrollbarWidth)return this.scrollbarWidth;var e=document.createElement("div");for(var t in C)C.hasOwnProperty(t)&&(e.style[t]=C[t]);document.body.appendChild(e);var n=e.offsetWidth-e.clientWidth;return document.body.removeChild(e),this.scrollbarWidth=n,n},adjustDialog:function(){if(this.refs.wrap&&this.scrollbarWidth){var e=this.refs.wrap.scrollHeight>document.documentElement.clientHeight;this.refs.wrap.style.paddingLeft=(!this.bodyIsOverflowing&&e?this.scrollbarWidth:"")+"px",this.refs.wrap.style.paddingRight=(this.bodyIsOverflowing&&!e?this.scrollbarWidth:"")+"px"}},resetAdjustments:function(){this.refs.wrap&&(this.refs.wrap.style.paddingLeft=this.refs.wrap.style.paddingLeft="")},render:function(){var e=this.props,t=e.prefixCls,n=this.getWrapStyle();return e.visible&&(n.display=null),c["default"].createElement("div",null,this.getMaskElement(),c["default"].createElement("div",{tabIndex:"-1",onKeyDown:this.onKeyDown,className:t+"-wrap "+(e.wrapClassName||""),ref:"wrap",onClick:this.onMaskClick,role:"dialog","aria-labelledby":e.title?this.titleId:null,style:n},this.getDialogElement()))}});t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(){}function l(e,t){var n={};return t.forEach(function(t){void 0!==e[t]&&(n[t]=e[t])}),n}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),p=n(1),f=r(p),d=n(4),h=r(d),y=n(410),v=r(y),m=function(e){function t(e){o(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.state={visible:e.visible},["onClose","cleanDialogContainer"].forEach(function(e){n[e]=n[e].bind(n)}),n}return a(t,e),c(t,[{key:"componentDidMount",value:function(){this.componentDidUpdate()}},{key:"componentWillReceiveProps",value:function(e){"visible"in e&&this.setState({visible:e.visible})}},{key:"shouldComponentUpdate",value:function(e,t){return!(!this.state.visible&&!t.visible)}},{key:"componentDidUpdate",value:function(){this.dialogRendered&&(this.dialogInstance=h["default"].unstable_renderSubtreeIntoContainer(this,this.getDialogElement(),this.getDialogContainer()))}},{key:"componentWillUnmount",value:function(){this.dialogContainer&&(this.state.visible?h["default"].unstable_renderSubtreeIntoContainer(this,this.getDialogElement({onAfterClose:this.cleanDialogContainer,onClose:s,visible:!1}),this.dialogContainer):this.cleanDialogContainer())}},{key:"onClose",value:function(e){this.props.onClose(e)}},{key:"getDialogContainer",value:function(){return this.dialogContainer||(this.dialogContainer=document.createElement("div"),document.body.appendChild(this.dialogContainer)),this.dialogContainer}},{key:"getDialogElement",value:function(e){var t=this.props,n=l(t,["className","closable","maskClosable","title","footer","mask","keyboard","animation","transitionName","maskAnimation","maskTransitionName","mousePosition","prefixCls","style","width","wrapStyle","height","zIndex","bodyStyle","wrapClassName"]);return n=u({},n,{onClose:this.onClose,visible:this.state.visible},e),f["default"].createElement(v["default"],u({},n,{key:"dialog"}),t.children)}},{key:"getElement",value:function(e){return this.dialogInstance.getElement(e)}},{key:"cleanDialogContainer",value:function(){this.dialogContainer&&(h["default"].unmountComponentAtNode(this.dialogContainer),document.body.removeChild(this.dialogContainer),this.dialogContainer=null)}},{key:"render",value:function(){return this.dialogRendered=this.dialogRendered||this.state.visible,null}}]),t}(f["default"].Component);m.defaultProps={className:"",mask:!0,keyboard:!0,closable:!0,maskClosable:!0,prefixCls:"rc-dialog",onClose:s},m.propTypes={className:p.PropTypes.string,keyboard:p.PropTypes.bool,wrapStyle:p.PropTypes.object,style:p.PropTypes.object,mask:p.PropTypes.bool,closable:p.PropTypes.bool,maskClosable:p.PropTypes.bool,prefixCls:p.PropTypes.string,visible:p.PropTypes.bool,onClose:p.PropTypes.func},t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=a["default"].createClass({displayName:"LazyRenderBox",propTypes:{className:i.PropTypes.string,visible:i.PropTypes.bool,hiddenClassName:i.PropTypes.string},shouldComponentUpdate:function(e){return e.hiddenClassName||e.visible},render:function(){var e=this.props.className;this.props.hiddenClassName&&!this.props.visible&&(e+=" "+this.props.hiddenClassName);var t=o({},this.props);return delete t.hiddenClassName,delete t.visible,t.className=e,a["default"].createElement("div",t)}});t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(411)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),s=r(a),l=n(4),u=r(l),c=n(28),p=r(c),f=n(416),d=r(f),h=s["default"].createClass({displayName:"Dropdown",propTypes:{minOverlayWidthMatchTrigger:a.PropTypes.bool,onVisibleChange:a.PropTypes.func,prefixCls:a.PropTypes.string,children:a.PropTypes.any,transitionName:a.PropTypes.string,overlayClassName:a.PropTypes.string,animation:a.PropTypes.any,align:a.PropTypes.object,overlayStyle:a.PropTypes.object,placement:a.PropTypes.string,trigger:a.PropTypes.array,showAction:a.PropTypes.array,hideAction:a.PropTypes.array,getPopupContainer:a.PropTypes.func},getDefaultProps:function(){return{minOverlayWidthMatchTrigger:!0,prefixCls:"rc-dropdown",trigger:["hover"],showAction:[],hideAction:[],overlayClassName:"",overlayStyle:{},defaultVisible:!1,onVisibleChange:function(){},placement:"bottomLeft"}},getInitialState:function(){var e=this.props;return"visible"in e?{visible:e.visible}:{visible:e.defaultVisible}},componentWillReceiveProps:function(e){var t=e.visible;void 0!==t&&this.setState({visible:t})},onClick:function(e){var t=this.props,n=t.overlay.props;"visible"in t||this.setState({visible:!1}),n.onClick&&n.onClick(e)},onVisibleChange:function(e){var t=this.props;"visible"in t||this.setState({visible:e}),t.onVisibleChange(e)},getMenuElement:function(){var e=this.props;return s["default"].cloneElement(e.overlay,{prefixCls:e.prefixCls+"-menu",onClick:this.onClick})},getPopupDomNode:function(){return this.refs.trigger.getPopupDomNode()},afterVisibleChange:function(e){if(e&&this.props.minOverlayWidthMatchTrigger){var t=this.getPopupDomNode(),n=u["default"].findDOMNode(this);n.offsetWidth>t.offsetWidth&&(t.style.width=n.offsetWidth+"px")}},render:function(){var e=this.props,t=e.prefixCls,n=e.children,r=e.transitionName,a=e.animation,l=e.align,u=e.placement,c=e.getPopupContainer,f=e.showAction,h=e.hideAction,y=e.overlayClassName,v=e.overlayStyle,m=e.trigger,g=o(e,["prefixCls","children","transitionName","animation","align","placement","getPopupContainer","showAction","hideAction","overlayClassName","overlayStyle","trigger"]);return s["default"].createElement(p["default"],i({},g,{prefixCls:t,ref:"trigger",popupClassName:y,popupStyle:v,builtinPlacements:d["default"],action:m,showAction:f,hideAction:h,popupPlacement:u,popupAlign:l,popupTransitionName:r,popupAnimation:a,popupVisible:this.state.visible,afterPopupVisibleChange:this.afterVisibleChange,popup:this.getMenuElement(),onPopupVisibleChange:this.onVisibleChange,getPopupContainer:c}),n)}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(414),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o=t.placements={topLeft:{points:["bl","tl"],overflow:n,offset:[0,-4],targetOffset:r},topCenter:{points:["bc","tc"],overflow:n,offset:[0,-4],targetOffset:r},topRight:{points:["br","tr"],overflow:n,offset:[0,-4],targetOffset:r},bottomLeft:{points:["tl","bl"],overflow:n,offset:[0,4],targetOffset:r},bottomCenter:{points:["tc","bc"],overflow:n,offset:[0,4],targetOffset:r},bottomRight:{points:["tr","br"],overflow:n,offset:[0,4],targetOffset:r}};t["default"]=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=window.getComputedStyle,r=n?n(e):e.currentStyle;if(r)return r[t.replace(/-(\w)/gi,function(e,t){return t.toUpperCase()})]}function i(e){for(var t=e,n=void 0;"body"!==(n=t.nodeName.toLowerCase());){var r=o(t,"overflowY");if("auto"===r||"scroll"===r)return t;t=t.parentNode}return"body"===n?t.ownerDocument:t}function a(e){return(0,c["default"])((0,l["default"])({},e),[m])}Object.defineProperty(t,"__esModule",{value:!0});var s=n(7),l=r(s),u=n(150),c=r(u),p=n(418),f=n(151),d=n(4),h=r(d),y=n(78),v=r(y),m={getForm:function(){return(0,l["default"])({},p.mixin.getForm.call(this),{validateFieldsAndScroll:this.validateFieldsAndScroll})},validateFieldsAndScroll:function(e,t,n){var r=this,o=(0,f.getParams)(e,t,n),a=o.names,s=o.callback,u=o.options,c=function(e,t){if(e){var n=void 0,o=void 0;for(var a in e)if(e.hasOwnProperty(a)){var c=r.getFieldInstance(a);if(c){var p=h["default"].findDOMNode(c),f=p.getBoundingClientRect().top;(void 0===o||o>f)&&(o=f,n=p)}}if(n){var d=u.container||i(n);(0,v["default"])(n,d,(0,l["default"])({onlyScrollIfNeeded:!0},u.scroll))}}"function"==typeof s&&s(e,t)};return this.validateFields(a,u,c)}};t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e,[s])}Object.defineProperty(t,"__esModule",{value:!0}),t.mixin=void 0;var i=n(150),a=r(i),s=t.mixin={getForm:function(){return{getFieldsValue:this.getFieldsValue,getFieldValue:this.getFieldValue,getFieldInstance:this.getFieldInstance,setFieldsValue:this.setFieldsValue,setFields:this.setFields,setFieldsInitialValue:this.setFieldsInitialValue,getFieldProps:this.getFieldProps,getFieldError:this.getFieldError,isFieldValidating:this.isFieldValidating,isFieldsValidating:this.isFieldsValidating,isSubmitting:this.isSubmitting,submit:this.submit,validateFields:this.validateFields,resetFields:this.resetFields}}};t["default"]=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e){e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var a=n(12),s=r(a),l=n(7),u=r(l),c=n(1),p=r(c),f=n(2),d=r(f),h=n(420),y=r(h),v=p["default"].createClass({displayName:"InputNumber",propTypes:{onChange:c.PropTypes.func,onKeyDown:c.PropTypes.func,onFocus:c.PropTypes.func,onBlur:c.PropTypes.func,max:c.PropTypes.number,min:c.PropTypes.number,step:c.PropTypes.oneOfType([c.PropTypes.number,c.PropTypes.string])},mixins:[y["default"]],getDefaultProps:function(){return{prefixCls:"rc-input-number"}},componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(){this.state.focused&&document.activeElement!==this.refs.input&&this.refs.input.focus()},onKeyDown:function(e){var t;38===e.keyCode?this.up(e):40===e.keyCode&&this.down(e);for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];(t=this.props).onKeyDown.apply(t,[e].concat(r))},getValueFromEvent:function(e){return e.target.value},focus:function(){this.refs.input.focus()},render:function(){var e,t=(0,u["default"])({},this.props),n=t.prefixCls,r=(0,d["default"])((e={},(0,s["default"])(e,n,!0),(0,s["default"])(e,t.className,!!t.className),(0,s["default"])(e,n+"-disabled",t.disabled),(0,s["default"])(e,n+"-focused",this.state.focused),e)),a="",l="",c=this.state.value;if(isNaN(c))a=n+"-handler-up-disabled",l=n+"-handler-down-disabled";else{var f=Number(c);f>=t.max&&(a=n+"-handler-up-disabled"),f<=t.min&&(l=n+"-handler-down-disabled")}var h=void 0;return h=this.state.focused?this.state.inputValue:this.state.value,void 0===h&&(h=""),delete t.defaultValue,delete t.prefixCls,p["default"].createElement("div",{className:r,style:t.style},p["default"].createElement("div",{className:n+"-handler-wrap"},p["default"].createElement("a",{unselectable:"unselectable",ref:"up",onClick:a?o:this.up,className:n+"-handler "+n+"-handler-up "+a},p["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-up-inner",onClick:i})),p["default"].createElement("a",{unselectable:"unselectable",ref:"down",onClick:l?o:this.down,className:n+"-handler "+n+"-handler-down "+l},p["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-down-inner",onClick:i}))),p["default"].createElement("div",{className:n+"-input-wrap"},p["default"].createElement("input",(0,u["default"])({},t,{style:null,className:n+"-input",autoComplete:"off",onFocus:this.onFocus,onBlur:this.onBlur,onKeyDown:this.onKeyDown,autoFocus:t.autoFocus,readOnly:t.readOnly,disabled:t.disabled,max:t.max,min:t.min,name:t.name,onChange:this.onChange,ref:"input",value:h}))))}});t["default"]=v,e.exports=t["default"]},function(e,t){"use strict";function n(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={getDefaultProps:function(){return{max:1/0,min:-(1/0),step:1,style:{},defaultValue:null,onChange:n,onKeyDown:n,onFocus:n,onBlur:n}},getInitialState:function(){var e=void 0,t=this.props;return e="value"in t?t.value:t.defaultValue,e=this.toPrecisionAsStep(e),{inputValue:e,value:e,focused:t.autoFocus}},componentWillReceiveProps:function(e){if("value"in e){var t=this.toPrecisionAsStep(e.value);this.setState({inputValue:t,value:t})}},onChange:function(e){this.setInputValue(this.getValueFromEvent(e).trim())},onFocus:function(){var e;this.setState({focused:!0}),(e=this.props).onFocus.apply(e,arguments)},onBlur:function(e){var t;this.setState({focused:!1});var n=this.getCurrentValidValue(this.getValueFromEvent(e).trim());this.setValue(n);for(var r=arguments.length,o=Array(r>1?r-1:0),i=1;i<r;i++)o[i-1]=arguments[i];(t=this.props).onBlur.apply(t,[e].concat(o))},getCurrentValidValue:function(e){var t=e,n=this.props;return""===t?t="":isNaN(t)?t=this.state.value:(t=Number(t),t<n.min&&(t=n.min),t>n.max&&(t=n.max)),this.toPrecisionAsStep(t)},setValue:function(e){"value"in this.props||this.setState({value:e,inputValue:e});var t=isNaN(e)||""===e?void 0:e;t!==this.state.value?this.props.onChange(t):this.setState({inputValue:this.state.value})},setInputValue:function(e){this.setState({inputValue:e})},getPrecision:function(){var e=this.props,t=e.step.toString();if(t.indexOf("e-")>=0)return parseInt(t.slice(t.indexOf("e-")+1),10);var n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n},getPrecisionFactor:function(){var e=this.getPrecision();return Math.pow(10,e)},toPrecisionAsStep:function(e){if(isNaN(e)||""===e)return e;var t=this.getPrecision();return Number(Number(e).toFixed(Math.abs(t)))},upStep:function(e){var t=this.props,n=t.step,r=t.min,o=this.getPrecisionFactor(),i=void 0;return i="number"==typeof e?(o*e+o*n)/o:r===-(1/0)?n:r,this.toPrecisionAsStep(i)},downStep:function(e){var t=this.props,n=t.step,r=t.min,o=this.getPrecisionFactor(),i=void 0;return i="number"==typeof e?(o*e-o*n)/o:r===-(1/0)?-n:r,this.toPrecisionAsStep(i)},step:function(e,t){t&&t.preventDefault();var n=this.props;if(!n.disabled){var r=this.getCurrentValidValue(this.state.value);if(this.setState({value:r}),!isNaN(r)){var o=this[e+"Step"](r);o>n.max||o<n.min||(this.setValue(o),this.setState({focused:!0}))}}},down:function(e){this.step("down",e)},up:function(e){this.step("up",e)}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(10),s=r(a),l=i["default"].createClass({displayName:"DOMWrap",propTypes:{tag:o.PropTypes.string,hiddenClassName:o.PropTypes.string,visible:o.PropTypes.bool},getDefaultProps:function(){return{tag:"div"}},render:function(){var e=(0,s["default"])({},this.props);e.visible||(e.className=e.className||"",e.className+=" "+e.hiddenClassName);var t=e.tag;return delete e.tag,delete e.hiddenClassName,delete e.visible,i["default"].createElement(t,e)}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=i["default"].createClass({displayName:"Divider",getDefaultProps:function(){return{disabled:!0}},render:function(){var e=this.props,t=e.className||"",n=e.rootPrefixCls;return t+=" "+(n+"-item-divider"),i["default"].createElement("li",{className:t})}});t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(152),s=r(a),l=n(10),u=r(l),c=n(55),p=i["default"].createClass({displayName:"Menu",propTypes:{openSubMenuOnMouseEnter:o.PropTypes.bool,closeSubMenuOnMouseLeave:o.PropTypes.bool,selectedKeys:o.PropTypes.arrayOf(o.PropTypes.string),defaultSelectedKeys:o.PropTypes.arrayOf(o.PropTypes.string),defaultOpenKeys:o.PropTypes.arrayOf(o.PropTypes.string),openKeys:o.PropTypes.arrayOf(o.PropTypes.string),mode:o.PropTypes.string,onClick:o.PropTypes.func,onSelect:o.PropTypes.func,onDeselect:o.PropTypes.func,onDestroy:o.PropTypes.func,openTransitionName:o.PropTypes.string,openAnimation:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.object]),level:o.PropTypes.number,eventKey:o.PropTypes.string,selectable:o.PropTypes.bool,children:o.PropTypes.any},mixins:[s["default"]],getDefaultProps:function(){return{openSubMenuOnMouseEnter:!0,closeSubMenuOnMouseLeave:!0,selectable:!0,onClick:c.noop,onSelect:c.noop,onOpen:c.noop,onClose:c.noop,onDeselect:c.noop,defaultSelectedKeys:[],defaultOpenKeys:[]}},getInitialState:function(){var e=this.props,t=e.defaultSelectedKeys,n=e.defaultOpenKeys;return"selectedKeys"in e&&(t=e.selectedKeys||[]),"openKeys"in e&&(n=e.openKeys||[]),{selectedKeys:t,openKeys:n}},componentWillReceiveProps:function(e){var t={};"selectedKeys"in e&&(t.selectedKeys=e.selectedKeys),"openKeys"in e&&(t.openKeys=e.openKeys),this.setState(t)},onDestroy:function(e){var t=this.state,n=this.props,r=t.selectedKeys,o=t.openKeys,i=r.indexOf(e);"selectedKeys"in n||i===-1||r.splice(i,1),i=o.indexOf(e),"openKeys"in n||i===-1||o.splice(i,1)},onItemHover:function(e){var t=this,n=e.item;"inline"!==this.props.mode&&!this.props.closeSubMenuOnMouseLeave&&n.isSubMenu&&!function(){var r=t.state.activeKey,o=t.getFlatInstanceArray().filter(function(e){return e&&e.props.eventKey===r})[0];o&&o.props.open&&t.onOpenChange({key:n.props.eventKey,item:e.item,open:!0})}(),this.onCommonItemHover(e)},onSelect:function(e){var t=this.props;if(t.selectable){var n=this.state.selectedKeys,r=e.key;n=t.multiple?n.concat([r]):[r],"selectedKeys"in t||this.setState({selectedKeys:n}),t.onSelect((0,u["default"])({},e,{selectedKeys:n}))}},onClick:function(e){this.props.onClick(e)},onOpenChange:function(e){var t=this.props,n=this.state.openKeys,r=!0;if(e.open)r=n.indexOf(e.key)===-1,r&&(n=n.concat(e.key));else{var o=n.indexOf(e.key);r=o!==-1,r&&(n=n.concat(),n.splice(o,1))}if(r){this.state.openKeys=n,"openKeys"in this.props||this.setState({openKeys:n});var i=(0,u["default"])({openKeys:n},e);e.open?t.onOpen(i):t.onClose(i)}},onDeselect:function(e){var t=this.props;if(t.selectable){var n=this.state.selectedKeys.concat(),r=e.key,o=n.indexOf(r);o!==-1&&n.splice(o,1),"selectedKeys"in t||this.setState({selectedKeys:n}),t.onDeselect((0,u["default"])({},e,{selectedKeys:n}))}},getOpenTransitionName:function(){var e=this.props,t=e.openTransitionName,n=e.openAnimation;return t||"string"!=typeof n||(t=e.prefixCls+"-open-"+n),t},isInlineMode:function(){return"inline"===this.props.mode},lastOpenSubMenu:function(){var e=this,t=[];return this.state.openKeys.length&&(t=this.getFlatInstanceArray().filter(function(t){return t&&e.state.openKeys.indexOf(t.props.eventKey)!==-1})),t[0]},renderMenuItem:function(e,t,n){if(!e)return null;var r=this.state,o={openKeys:r.openKeys,selectedKeys:r.selectedKeys,openSubMenuOnMouseEnter:this.props.openSubMenuOnMouseEnter};return this.renderCommonMenuItem(e,t,n,o)},render:function(){var e=(0,u["default"])({},this.props);return e.className+=" "+e.prefixCls+"-root",this.renderRoot(e)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(15),l=r(s),u=n(2),c=r(u),p=n(55),f=a["default"].createClass({displayName:"MenuItem",propTypes:{rootPrefixCls:i.PropTypes.string,eventKey:i.PropTypes.string,active:i.PropTypes.bool,children:i.PropTypes.any,selectedKeys:i.PropTypes.array,disabled:i.PropTypes.bool,title:i.PropTypes.string,onSelect:i.PropTypes.func,onClick:i.PropTypes.func,onDeselect:i.PropTypes.func,parentMenu:i.PropTypes.object,onItemHover:i.PropTypes.func,onDestroy:i.PropTypes.func,onMouseEnter:i.PropTypes.func,onMouseLeave:i.PropTypes.func},getDefaultProps:function(){return{onSelect:p.noop,onMouseEnter:p.noop,onMouseLeave:p.noop}},componentWillUnmount:function(){var e=this.props;e.onDestroy&&e.onDestroy(e.eventKey),e.parentMenu.menuItemInstance===this&&this.clearMenuItemMouseLeaveTimer()},onKeyDown:function(e){var t=e.keyCode;if(t===l["default"].ENTER)return this.onClick(e),!0},onMouseLeave:function(e){var t=this,n=this.props,r=n.eventKey,o=n.parentMenu;o.menuItemInstance=this,o.menuItemMouseLeaveFn=function(){t.isMounted()&&n.active&&n.onItemHover({key:r,item:t,hover:!1,trigger:"mouseleave"})},o.menuItemMouseLeaveTimer=setTimeout(o.menuItemMouseLeaveFn,30),n.onMouseLeave({key:r,domEvent:e})},onMouseEnter:function(e){var t=this.props,n=t.parentMenu;this.clearMenuItemMouseLeaveTimer(n.menuItemInstance!==this),n.subMenuInstance&&n.subMenuInstance.clearSubMenuTimers(!0);var r=t.eventKey;t.onItemHover({key:r,item:this,hover:!0,trigger:"mouseenter"}),t.onMouseEnter({key:r,domEvent:e})},onClick:function(e){var t=this.props,n=this.isSelected(),r=t.eventKey,o={key:r,keyPath:[r],item:this,domEvent:e};t.onClick(o),t.multiple?n?t.onDeselect(o):t.onSelect(o):n||t.onSelect(o)},getPrefixCls:function(){return this.props.rootPrefixCls+"-item"},getActiveClassName:function(){return this.getPrefixCls()+"-active"},getSelectedClassName:function(){return this.getPrefixCls()+"-selected"},getDisabledClassName:function(){return this.getPrefixCls()+"-disabled"},clearMenuItemMouseLeaveTimer:function(e){var t=this.props,n=t.parentMenu;n.menuItemMouseLeaveTimer&&(clearTimeout(n.menuItemMouseLeaveTimer),n.menuItemMouseLeaveTimer=null,e&&n.menuItemMouseLeaveFn&&n.menuItemMouseLeaveFn(),n.menuItemMouseLeaveFn=null)},isSelected:function(){return this.props.selectedKeys.indexOf(this.props.eventKey)!==-1},render:function(){var e=this.props,t=this.isSelected(),n={};n[this.getActiveClassName()]=!e.disabled&&e.active,n[this.getSelectedClassName()]=t,n[this.getDisabledClassName()]=e.disabled,n[this.getPrefixCls()]=!0,n[e.className]=!!e.className;var r=o({},e.attribute,{title:e.title,className:(0,c["default"])(n),role:"menuitem","aria-selected":t,"aria-disabled":e.disabled}),i={};e.disabled||(i={onClick:this.onClick,onMouseLeave:this.onMouseLeave,onMouseEnter:this.onMouseEnter});var s=o({},e.style);return"inline"===e.mode&&(s.paddingLeft=e.inlineIndent*e.level),a["default"].createElement("li",o({style:s},r,i),e.children)}});f.isMenuItem=1,t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=i["default"].createClass({displayName:"MenuItemGroup",propTypes:{renderMenuItem:o.PropTypes.func,index:o.PropTypes.number},getDefaultProps:function(){return{disabled:!0}},renderInnerMenuItem:function(e,t){var n=this.props.renderMenuItem;return n(e,this.props.index,t)},render:function(){var e=this.props,t=e.className||"",n=e.rootPrefixCls;t+=" "+n+"-item-group";var r=n+"-item-group-title",o=n+"-item-group-list";return i["default"].createElement("li",{className:t},i["default"].createElement("div",{className:r},e.title),i["default"].createElement("ul",{className:o},i["default"].Children.map(e.children,this.renderInnerMenuItem)))}});a.isMenuItemGroup=!0,t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(428),s=r(a),l=n(1),u=r(l),c=n(15),p=r(c),f=n(502),d=r(f),h=n(2),y=r(h),v=n(55),m=u["default"].createClass({displayName:"SubMenu",propTypes:{parentMenu:l.PropTypes.object,title:l.PropTypes.node,children:l.PropTypes.any,selectedKeys:l.PropTypes.array,openKeys:l.PropTypes.array,onClick:l.PropTypes.func,onOpenChange:l.PropTypes.func,rootPrefixCls:l.PropTypes.string,eventKey:l.PropTypes.string,multiple:l.PropTypes.bool,active:l.PropTypes.bool,onSelect:l.PropTypes.func,closeSubMenuOnMouseLeave:l.PropTypes.bool,openSubMenuOnMouseEnter:l.PropTypes.bool,onDeselect:l.PropTypes.func,onDestroy:l.PropTypes.func,onItemHover:l.PropTypes.func,onMouseEnter:l.PropTypes.func,onMouseLeave:l.PropTypes.func,onTitleMouseEnter:l.PropTypes.func,onTitleMouseLeave:l.PropTypes.func,onTitleClick:l.PropTypes.func},mixins:[n(427)],getDefaultProps:function(){return{onMouseEnter:v.noop,onMouseLeave:v.noop,onTitleMouseEnter:v.noop,onTitleMouseLeave:v.noop,onTitleClick:v.noop,title:""}},getInitialState:function(){return this.isSubMenu=1,{defaultActiveFirst:!1}},componentWillUnmount:function(){var e=this.props;e.onDestroy&&e.onDestroy(e.eventKey),e.parentMenu.subMenuInstance===this&&this.clearSubMenuTimers()},onDestroy:function(e){this.props.onDestroy(e)},onKeyDown:function(e){var t=e.keyCode,n=this.menuInstance,r=this.isOpen();if(t===p["default"].ENTER)return this.onTitleClick(e), this.setState({defaultActiveFirst:!0}),!0;if(t===p["default"].RIGHT)return r?n.onKeyDown(e):(this.triggerOpenChange(!0),this.setState({defaultActiveFirst:!0})),!0;if(t===p["default"].LEFT){var o=void 0;if(!r)return;return o=n.onKeyDown(e),o||(this.triggerOpenChange(!1),o=!0),o}return!r||t!==p["default"].UP&&t!==p["default"].DOWN?void 0:n.onKeyDown(e)},onOpenChange:function(e){this.props.onOpenChange(this.addKeyPath(e))},onMouseEnter:function(e){var t=this.props;this.clearSubMenuLeaveTimer(t.parentMenu.subMenuInstance!==this),t.onMouseEnter({key:t.eventKey,domEvent:e})},onTitleMouseEnter:function(e){var t=this.props,n=t.parentMenu;this.clearSubMenuTitleLeaveTimer(n.subMenuInstance!==this),n.menuItemInstance&&n.menuItemInstance.clearMenuItemMouseLeaveTimer(!0),t.onItemHover({key:t.eventKey,item:this,hover:!0,trigger:"mouseenter"}),t.openSubMenuOnMouseEnter&&this.triggerOpenChange(!0),this.setState({defaultActiveFirst:!1}),t.onTitleMouseEnter({key:t.eventKey,domEvent:e})},onTitleMouseLeave:function(e){var t=this,n=this.props,r=n.parentMenu;r.subMenuInstance=this,r.subMenuTitleLeaveFn=function(){var r=n.eventKey;t.isMounted()&&("inline"===n.mode&&n.active&&n.onItemHover({key:r,item:t,hover:!1,trigger:"mouseleave"}),n.onTitleMouseLeave({key:n.eventKey,domEvent:e}))},r.subMenuTitleLeaveTimer=setTimeout(r.subMenuTitleLeaveFn,100)},onMouseLeave:function(e){var t=this,n=this.props,r=n.parentMenu;r.subMenuInstance=this,r.subMenuLeaveFn=function(){var r=n.eventKey;t.isMounted()&&("inline"!==n.mode&&(n.active&&n.onItemHover({key:r,item:t,hover:!1,trigger:"mouseleave"}),t.isOpen()&&n.closeSubMenuOnMouseLeave&&t.triggerOpenChange(!1)),n.onMouseLeave({key:r,domEvent:e}))},r.subMenuLeaveTimer=setTimeout(r.subMenuLeaveFn,100)},onTitleClick:function(e){var t=this.props;t.onTitleClick({key:t.eventKey,domEvent:e}),t.openSubMenuOnMouseEnter||(this.triggerOpenChange(!this.isOpen(),"click"),this.setState({defaultActiveFirst:!1}))},onSubMenuClick:function(e){this.props.onClick(this.addKeyPath(e))},onSelect:function(e){this.props.onSelect(e)},onDeselect:function(e){this.props.onDeselect(e)},getPrefixCls:function(){return this.props.rootPrefixCls+"-submenu"},getActiveClassName:function(){return this.getPrefixCls()+"-active"},getDisabledClassName:function(){return this.getPrefixCls()+"-disabled"},getSelectedClassName:function(){return this.getPrefixCls()+"-selected"},getOpenClassName:function(){return this.props.rootPrefixCls+"-submenu-open"},saveMenuInstance:function(e){this.menuInstance=e},addKeyPath:function(e){return i({},e,{keyPath:(e.keyPath||[]).concat(this.props.eventKey)})},triggerOpenChange:function(e,t){var n=this.props.eventKey;this.onOpenChange({key:n,item:this,trigger:t,open:e})},clearSubMenuTimers:function(e){this.clearSubMenuLeaveTimer(e),this.clearSubMenuTitleLeaveTimer(e)},clearSubMenuTitleLeaveTimer:function(e){var t=this.props.parentMenu;t.subMenuTitleLeaveTimer&&(clearTimeout(t.subMenuTitleLeaveTimer),t.subMenuTitleLeaveTimer=null,e&&t.subMenuTitleLeaveFn&&t.subMenuTitleLeaveFn(),t.subMenuTitleLeaveFn=null)},clearSubMenuLeaveTimer:function(e){var t=this.props.parentMenu;t.subMenuLeaveTimer&&(clearTimeout(t.subMenuLeaveTimer),t.subMenuLeaveTimer=null,e&&t.subMenuLeaveFn&&t.subMenuLeaveFn(),t.subMenuLeaveFn=null)},isChildrenSelected:function(){var e={find:!1};return(0,v.loopMenuItemRecusively)(this.props.children,this.props.selectedKeys,e),e.find},isOpen:function(){return this.props.openKeys.indexOf(this.props.eventKey)!==-1},renderChildren:function(e){var t=this.props,n={mode:"horizontal"===t.mode?"vertical":t.mode,visible:this.isOpen(),level:t.level+1,inlineIndent:t.inlineIndent,focusable:!1,onClick:this.onSubMenuClick,onSelect:this.onSelect,onDeselect:this.onDeselect,onDestroy:this.onDestroy,selectedKeys:t.selectedKeys,eventKey:t.eventKey+"-menu-",openKeys:t.openKeys,openTransitionName:t.openTransitionName,openAnimation:t.openAnimation,onOpenChange:this.onOpenChange,closeSubMenuOnMouseLeave:t.closeSubMenuOnMouseLeave,defaultActiveFirst:this.state.defaultActiveFirst,multiple:t.multiple,prefixCls:t.rootPrefixCls,id:this._menuId,ref:this.saveMenuInstance};return u["default"].createElement(s["default"],n,e)},render:function(){var e,t=this.isOpen();this.haveOpen=this.haveOpen||t;var n=this.props,r=this.getPrefixCls(),a=(e={},o(e,n.className,!!n.className),o(e,r+"-"+n.mode,1),e);a[this.getOpenClassName()]=t,a[this.getActiveClassName()]=n.active,a[this.getDisabledClassName()]=n.disabled,a[this.getSelectedClassName()]=this.isChildrenSelected(),this._menuId=this._menuId||(0,d["default"])(),a[r]=!0,a[r+"-"+n.mode]=1;var s={},l={},c={};n.disabled||(s={onClick:this.onTitleClick},l={onMouseLeave:this.onMouseLeave,onMouseEnter:this.onMouseEnter},c={onMouseEnter:this.onTitleMouseEnter,onMouseLeave:this.onTitleMouseLeave});var p={};return"inline"===n.mode&&(p.paddingLeft=n.inlineIndent*n.level),u["default"].createElement("li",i({className:(0,y["default"])(a)},l),u["default"].createElement("div",i({style:p,className:r+"-title"},c,s,{"aria-open":t,"aria-owns":this._menuId,"aria-haspopup":"true"}),n.title),this.renderChildren(n.children))}});m.isSubMenu=1,t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(15),i=r(o),a=n(20),s=r(a),l=n(171),u=r(l),c=n(4),p=r(c);t["default"]={componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(){"inline"!==this.props.mode&&(this.props.open?this.bindRootCloseHandlers():this.unbindRootCloseHandlers())},handleDocumentKeyUp:function(e){e.keyCode===i["default"].ESC&&this.props.onItemHover({key:this.props.eventKey,item:this,hover:!1})},handleDocumentClick:function(e){if(!(0,u["default"])(p["default"].findDOMNode(this),e.target)){var t=this.props;t.onItemHover({hover:!1,item:this,key:this.props.eventKey}),this.triggerOpenChange(!1)}},bindRootCloseHandlers:function(){this._onDocumentClickListener||(this._onDocumentClickListener=(0,s["default"])(document,"click",this.handleDocumentClick),this._onDocumentKeyupListener=(0,s["default"])(document,"keyup",this.handleDocumentKeyUp))},unbindRootCloseHandlers:function(){this._onDocumentClickListener&&(this._onDocumentClickListener.remove(),this._onDocumentClickListener=null),this._onDocumentKeyupListener&&(this._onDocumentKeyupListener.remove(),this._onDocumentKeyupListener=null)},componentWillUnmount:function(){this.unbindRootCloseHandlers()}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},a=n(1),s=r(a),l=n(152),u=r(l),c=n(10),p=r(c),f=n(9),d=r(f),h=s["default"].createClass({displayName:"SubPopupMenu",propTypes:{onSelect:a.PropTypes.func,onClick:a.PropTypes.func,onDeselect:a.PropTypes.func,onOpenChange:a.PropTypes.func,onDestroy:a.PropTypes.func,openTransitionName:a.PropTypes.string,openAnimation:a.PropTypes.oneOfType([a.PropTypes.string,a.PropTypes.object]),openKeys:a.PropTypes.arrayOf(a.PropTypes.string),closeSubMenuOnMouseLeave:a.PropTypes.bool,visible:a.PropTypes.bool,children:a.PropTypes.any},mixins:[u["default"]],onDeselect:function(e){this.props.onDeselect(e)},onSelect:function(e){this.props.onSelect(e)},onClick:function(e){this.props.onClick(e)},onOpenChange:function(e){this.props.onOpenChange(e)},onDestroy:function(e){this.props.onDestroy(e)},onItemHover:function(e){this.onCommonItemHover(e)},getOpenTransitionName:function(){return this.props.openTransitionName},renderMenuItem:function(e,t,n){var r=this.props,o={openKeys:r.openKeys,selectedKeys:r.selectedKeys,openSubMenuOnMouseEnter:!0};return this.renderCommonMenuItem(e,t,n,o)},render:function(){var e=this.renderFirst;if(this.renderFirst=1,this.haveOpened=this.haveOpened||this.props.visible,!this.haveOpened)return null;var t=!0;!e&&this.props.visible&&(t=!1);var n=(0,p["default"])({},this.props);n.className+=" "+n.prefixCls+"-sub";var r={};return n.openTransitionName?r.transitionName=n.openTransitionName:"object"===i(n.openAnimation)&&(r.animation=(0,p["default"])({},n.openAnimation),t||delete r.animation.appear),s["default"].createElement(d["default"],o({},r,{showProp:"visible",component:"",transitionAppear:t}),this.renderRoot(n))}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=n(2),l=r(s),u=a["default"].createClass({displayName:"Notice",propTypes:{duration:i.PropTypes.number,onClose:i.PropTypes.func,children:i.PropTypes.any},getDefaultProps:function(){return{onEnd:function(){},onClose:function(){},duration:1.5,style:{right:"50%"}}},componentDidMount:function(){var e=this;this.props.duration&&(this.closeTimer=setTimeout(function(){e.close()},1e3*this.props.duration))},componentWillUnmount:function(){this.clearCloseTimer()},clearCloseTimer:function(){this.closeTimer&&(clearTimeout(this.closeTimer),this.closeTimer=null)},close:function(){this.clearCloseTimer(),this.props.onClose()},render:function(){var e,t=this.props,n=t.prefixCls+"-notice",r=(e={},o(e,""+n,1),o(e,n+"-closable",t.closable),o(e,t.className,!!t.className),e);return a["default"].createElement("div",{className:(0,l["default"])(r),style:t.style},a["default"].createElement("div",{className:n+"-content"},t.children),t.closable?a["default"].createElement("a",{tabIndex:"0",onClick:this.close,className:n+"-close"},a["default"].createElement("span",{className:n+"-close-x"})):null)}});t["default"]=u,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(){return"rcNotification_"+P+"_"+b++}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(4),c=r(u),p=n(9),f=r(p),d=n(83),h=r(d),y=n(2),v=r(y),m=n(429),g=r(m),b=0,P=Date.now(),C=l["default"].createClass({displayName:"Notification",propTypes:{prefixCls:s.PropTypes.string,transitionName:s.PropTypes.string,animation:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.object]),style:s.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-notification",animation:"fade",style:{top:65,left:"50%"}}},getInitialState:function(){return{notices:[]}},getTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},add:function(e){var t=e.key=e.key||i();this.setState(function(n){var r=n.notices;if(!r.filter(function(e){return e.key===t}).length)return{notices:r.concat(e)}})},remove:function(e){this.setState(function(t){return{notices:t.notices.filter(function(t){return t.key!==e})}})},render:function(){var e,t=this,n=this.props,r=this.state.notices.map(function(e){var r=(0,h["default"])(t.remove.bind(t,e.key),e.onClose);return l["default"].createElement(g["default"],a({prefixCls:n.prefixCls},e,{onClose:r}),e.content)}),i=(e={},o(e,n.prefixCls,1),o(e,n.className,!!n.className),e);return l["default"].createElement("div",{className:(0,v["default"])(i),style:n.style},l["default"].createElement(f["default"],{transitionName:this.getTransitionName()},r))}});C.newInstance=function(e){var t=e||{},n=document.createElement("div");document.body.appendChild(n);var r=c["default"].render(l["default"].createElement(C,t),n);return{notice:function(e){r.add(e)},removeNotice:function(e){r.remove(e)},component:r,destroy:function(){c["default"].unmountComponentAtNode(n),document.body.removeChild(n)}}},t["default"]=C,e.exports=t["default"]},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(a)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=i,n=a,r=!0,s=u=void 0}},s=n(1),l=n(154),u=function(e){function t(e){var n=this;r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.state={current:e.current,_current:e.current},["_handleChange","_changeSize","_go","_buildOptionText"].forEach(function(e){return n[e]=n[e].bind(n)})}return o(t,e),i(t,[{key:"_buildOptionText",value:function(e){return e+" "+this.props.locale.items_per_page}},{key:"_changeSize",value:function(e){this.props.changeSize(Number(e))}},{key:"_handleChange",value:function(e){var t=e.target.value;this.setState({_current:t})}},{key:"_go",value:function(e){var t=e.target.value;if(""!==t){var n=Number(this.state._current);if(isNaN(n)&&(n=this.state.current),e.keyCode===l.ENTER){var r=this.props.quickGo(n);this.setState({_current:r,current:r})}}}},{key:"render",value:function(){var e=this,t=this.props,n=this.state,r=t.locale,o=t.rootPrefixCls+"-options",i=t.changeSize,a=t.quickGo,l=t.buildOptionText||this._buildOptionText,u=t.selectComponentClass,c=null,p=null;return i||a?(i&&u&&!function(){var n=u.Option,r=t.pageSize||t.pageSizeOptions[0],i=t.pageSizeOptions.map(function(e,t){return s.createElement(n,{key:t,value:e},l(e))});c=s.createElement(u,{prefixCls:t.selectPrefixCls,showSearch:!1,className:o+"-size-changer",optionLabelProp:"children",dropdownMatchSelectWidth:!1,value:r+"",onChange:e._changeSize},i)}(),a&&(p=s.createElement("div",{className:o+"-quick-jumper"},r.jump_to,s.createElement("input",{type:"text",value:n._current,onChange:this._handleChange.bind(this),onKeyUp:this._go.bind(this)}),r.page)),s.createElement("div",{className:""+o},c,p)):null}}]),t}(s.Component);u.propTypes={changeSize:s.PropTypes.func,quickGo:s.PropTypes.func,selectComponentClass:s.PropTypes.func,current:s.PropTypes.number,pageSizeOptions:s.PropTypes.arrayOf(s.PropTypes.string),pageSize:s.PropTypes.number,buildOptionText:s.PropTypes.func,locale:s.PropTypes.object},u.defaultProps={pageSizeOptions:["10","20","30","40"]},e.exports=u},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(a)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=i,n=a,r=!0,s=u=void 0}},s=n(1),l=function(e){function t(){r(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.rootPrefixCls+"-item",n=t+" "+t+"-"+e.page;return e.active&&(n=n+" "+t+"-active"),s.createElement("li",{title:e.page,className:n,onClick:e.onClick},s.createElement("a",null,e.page))}}]),t}(s.Component);l.propTypes={page:s.PropTypes.number,active:s.PropTypes.bool,last:s.PropTypes.bool,locale:s.PropTypes.object},e.exports=l},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(){}var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,i);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(a)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=i,n=a,r=!0,s=u=void 0}},l=n(1),u=n(432),c=n(431),p=n(154),f=n(155),d=function(e){function t(e){var n=this;r(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e);var o=e.onChange!==i,a="current"in e;a&&!o&&console.warn("Warning: You provided a `current` prop to a Pagination component without an `onChange` handler. This will render a read-only component.");var l=e.defaultCurrent;"current"in e&&(l=e.current);var u=e.defaultPageSize;"pageSize"in e&&(u=e.pageSize),this.state={current:l,_current:l,pageSize:u},["render","_handleChange","_handleKeyUp","_handleKeyDown","_changePageSize","_isValid","_prev","_next","_hasPrev","_hasNext","_jumpPrev","_jumpNext"].forEach(function(e){return n[e]=n[e].bind(n)})}return o(t,e),a(t,[{key:"componentWillReceiveProps",value:function(e){if("current"in e&&this.setState({current:e.current,_current:e.current}),"pageSize"in e){var t={},n=this.state.current,r=this._calcPage(e.pageSize);n=n>r?r:n,"current"in e||(t.current=n,t._current=n),t.pageSize=e.pageSize,this.setState(t)}}},{key:"_calcPage",value:function(e){var t=e;return"undefined"==typeof t&&(t=this.state.pageSize),Math.floor((this.props.total-1)/t)+1}},{key:"_isValid",value:function(e){return"number"==typeof e&&e>=1&&e!==this.state.current}},{key:"_handleKeyDown",value:function(e){e.keyCode!==p.ARROW_UP&&e.keyCode!==p.ARROW_DOWN||e.preventDefault()}},{key:"_handleKeyUp",value:function(e){var t=e.target.value,n=void 0;n=""===t?t:isNaN(Number(t))?this.state._current:Number(t),this.setState({_current:n}),e.keyCode===p.ENTER?this._handleChange(n):e.keyCode===p.ARROW_UP?this._handleChange(n-1):e.keyCode===p.ARROW_DOWN&&this._handleChange(n+1)}},{key:"_changePageSize",value:function(e){var t=this.state.current,n=this._calcPage(e);t=t>n?n:t,"number"==typeof e&&("pageSize"in this.props||this.setState({pageSize:e}),"current"in this.props||this.setState({current:t,_current:t})),this.props.onShowSizeChange(t,e)}},{key:"_handleChange",value:function(e){var t=e;return this._isValid(t)?(t>this._calcPage()&&(t=this._calcPage()),"current"in this.props||this.setState({current:t,_current:t}),this.props.onChange(t),t):this.state.current}},{key:"_prev",value:function(){this._hasPrev()&&this._handleChange(this.state.current-1)}},{key:"_next",value:function(){this._hasNext()&&this._handleChange(this.state.current+1)}},{key:"_jumpPrev",value:function(){this._handleChange(Math.max(1,this.state.current-5))}},{key:"_jumpNext",value:function(){this._handleChange(Math.min(this._calcPage(),this.state.current+5))}},{key:"_hasPrev",value:function(){return this.state.current>1}},{key:"_hasNext",value:function(){return this.state.current<this._calcPage()}},{key:"render",value:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=this._calcPage(),o=[],i=null,a=null,s=null,p=null;if(e.simple)return l.createElement("ul",{className:n+" "+n+"-simple "+e.className},l.createElement("li",{title:t.prev_page,onClick:this._prev,className:(this._hasPrev()?"":n+"-disabled ")+(n+"-prev")},l.createElement("a",null)),l.createElement("div",{title:this.state.current+"/"+r,className:n+"-simple-pager"},l.createElement("input",{type:"text",value:this.state._current,onKeyDown:this._handleKeyDown,onKeyUp:this._handleKeyUp,onChange:this._handleKeyUp}),l.createElement("span",{className:n+"-slash"},"\uff0f"),r),l.createElement("li",{title:t.next_page,onClick:this._next,className:(this._hasNext()?"":n+"-disabled ")+(n+"-next")},l.createElement("a",null)));if(r<=9)for(var f=1;f<=r;f++){var d=this.state.current===f;o.push(l.createElement(u,{locale:t,rootPrefixCls:n,onClick:this._handleChange.bind(this,f),key:f,page:f,active:d}))}else{i=l.createElement("li",{title:t.prev_5,key:"prev",onClick:this._jumpPrev,className:n+"-jump-prev"},l.createElement("a",null)),a=l.createElement("li",{title:t.next_5,key:"next",onClick:this._jumpNext,className:n+"-jump-next"},l.createElement("a",null)),p=l.createElement(u,{locale:e.locale,last:!0,rootPrefixCls:n,onClick:this._handleChange.bind(this,r),key:r,page:r,active:!1}),s=l.createElement(u,{locale:e.locale,rootPrefixCls:n,onClick:this._handleChange.bind(this,1),key:1,page:1,active:!1});var h=this.state.current,y=Math.max(1,h-2),v=Math.min(h+2,r);h-1<=2&&(v=5),r-h<=2&&(y=r-4);for(var f=y;f<=v;f++){var d=h===f;o.push(l.createElement(u,{locale:e.locale,rootPrefixCls:n,onClick:this._handleChange.bind(this,f),key:f,page:f,active:d}))}h-1>=4&&o.unshift(i),r-h>=4&&o.push(a),1!==y&&o.unshift(s),v!==r&&o.push(p)}var m=null;return e.showTotal&&(m=l.createElement("span",{className:n+"-total-text"},e.showTotal(e.total))),l.createElement("ul",{className:n+" "+e.className,unselectable:"unselectable"},m,l.createElement("li",{title:t.prev_page,onClick:this._prev,className:(this._hasPrev()?"":n+"-disabled ")+(n+"-prev")},l.createElement("a",null)),o,l.createElement("li",{title:t.next_page,onClick:this._next,className:(this._hasNext()?"":n+"-disabled ")+(n+"-next")},l.createElement("a",null)),l.createElement(c,{locale:e.locale,rootPrefixCls:n,selectComponentClass:e.selectComponentClass,selectPrefixCls:e.selectPrefixCls,changeSize:this.props.showSizeChanger?this._changePageSize.bind(this):null,current:this.state.current,pageSize:this.state.pageSize,pageSizeOptions:this.props.pageSizeOptions,quickGo:this.props.showQuickJumper?this._handleChange.bind(this):null}))}}]),t}(l.Component);d.propTypes={current:l.PropTypes.number,defaultCurrent:l.PropTypes.number,total:l.PropTypes.number,pageSize:l.PropTypes.number,defaultPageSize:l.PropTypes.number,onChange:l.PropTypes.func,showSizeChanger:l.PropTypes.bool,onShowSizeChange:l.PropTypes.func,selectComponentClass:l.PropTypes.func,showQuickJumper:l.PropTypes.bool,pageSizeOptions:l.PropTypes.arrayOf(l.PropTypes.string),showTotal:l.PropTypes.func,locale:l.PropTypes.object},d.defaultProps={defaultCurrent:1,total:0,defaultPageSize:10,onChange:i,className:"",selectPrefixCls:"rc-select",prefixCls:"rc-pagination",selectComponentClass:null,showQuickJumper:!1,showSizeChanger:!1,onShowSizeChange:i,locale:f},e.exports=d},function(e,t,n){"use strict";e.exports=n(433)},function(e,t,n){"use strict";var r=n(10),o=n(1),i={strokeWidth:1,strokeColor:"#3FC7FA",trailWidth:1,trailColor:"#D9D9D9"},a=o.createClass({displayName:"Line",render:function(){var e=r({},this.props),t={strokeDasharray:"100px, 100px",strokeDashoffset:100-e.percent+"px",transition:"stroke-dashoffset 0.6s ease 0s, stroke 0.6s linear"};["strokeWidth","strokeColor","trailWidth","trailColor"].forEach(function(t){return"trailWidth"===t&&!e.trailWidth&&e.strokeWidth?void(e.trailWidth=e.strokeWidth):"strokeWidth"===t&&e.strokeWidth&&(!parseFloat(e.strokeWidth)||parseFloat(e.strokeWidth)>100||parseFloat(e.strokeWidth)<0)?void(e[t]=i[t]):void(e[t]||(e[t]=i[t]))});var n=e.strokeWidth,a=n/2,s=100-n/2,l="M "+a+","+a+" L "+s+","+a,u="0 0 100 "+n;return o.createElement("svg",{className:"rc-progress-line",viewBox:u,preserveAspectRatio:"none"},o.createElement("path",{className:"rc-progress-line-trail",d:l,strokeLinecap:"round",stroke:e.trailColor,strokeWidth:e.trailWidth,fillOpacity:"0"}),o.createElement("path",{className:"rc-progress-line-path",d:l,strokeLinecap:"round",stroke:e.strokeColor,strokeWidth:e.strokeWidth,fillOpacity:"0",style:t}))}}),s=o.createClass({displayName:"Circle",render:function(){var e=r({},this.props),t=e.strokeWidth,n=50-t/2,a="M 50,50 m 0,-"+n+"\n a "+n+","+n+" 0 1 1 0,"+2*n+"\n a "+n+","+n+" 0 1 1 0,-"+2*n,s=2*Math.PI*n,l={strokeDasharray:s+"px "+s+"px",strokeDashoffset:(100-e.percent)/100*s+"px",transition:"stroke-dashoffset 0.6s ease 0s, stroke 0.6s ease"};return["strokeWidth","strokeColor","trailWidth","trailColor"].forEach(function(t){return"trailWidth"===t&&!e.trailWidth&&e.strokeWidth?void(e.trailWidth=e.strokeWidth):void(e[t]||(e[t]=i[t]))}),o.createElement("svg",{className:"rc-progress-circle",viewBox:"0 0 100 100"},o.createElement("path",{className:"rc-progress-circle-trail",d:a,stroke:e.trailColor,strokeWidth:e.trailWidth,fillOpacity:"0"}),o.createElement("path",{className:"rc-progress-circle-path",d:a,strokeLinecap:"round",stroke:e.strokeColor,strokeWidth:e.strokeWidth,fillOpacity:"0",style:l}))}});e.exports={Line:a,Circle:s}},function(e,t,n){"use strict";e.exports=n(435)},function(e,t,n){(function(r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function i(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):i(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=o(p),d=n(4),h=n(440),y=n(438),v=o(y),m={easeInElastic:function(e,t,n){var r=e,o=t>=1?t:1,i=(n||1)/(t<1?t:1),a=i/Math.PI*2*(Math.asin(1/o)||0);return-(o*Math.pow(2,10*(r-=1))*Math.sin((r-a)*i))},easeOutElastic:function(e,t,n){var r=t>=1?t:1,o=(n||1)/(t<1?t:1),i=o/Math.PI*2*(Math.asin(1/r)||0);return r*Math.pow(2,-10*e)*Math.sin((e-i)*o)+1},easeInOutElastic:function(e,t,n){var r=e,o=t>=1?t:1,i=(n||1)/(t<1?t:1),a=i/Math.PI*2*(Math.asin(1/o)||0);return r*=2,r<1?-.5*(o*Math.pow(2,10*(r-=1))*Math.sin((r-a)*i)):o*Math.pow(2,-10*(r-=1))*Math.sin((r-a)*i)*.5+1},easeInBounce:function(e){var t=e,n=1-t;return n<1/2.75?1-7.5625*t*t:t<2/2.75?1-(7.5625*(t-=1.5/2.75)*t+.75):t<2.5/2.75?1-(7.5625*(t-=2.25/2.75)*t+.9375):1-(7.5625*(t-=2.625/2.75)*t+.984375)},easeOutBounce:function(e){var t=e;return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},easeInOutBounce:function(e){var t=e,n=t<.5;return t=n?1-2*t:2*t-1,t=t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375,n?.5*(1-t):.5*t+.5}},g=void 0;"undefined"!=typeof document&&"undefined"!=typeof window?(g=n(515),Object.keys(m).forEach(function(e){g.Easings&&(g.Easings[e]=m[e])})):g=function(){var e=arguments[arguments.length-1];r(function(){return e()})};var b={easeInBack:[.6,-.28,.735,.045],easeOutBack:[.175,.885,.32,1.275],easeInOutBack:[.68,-.55,.265,1.55]},P="ant-queue-anim-placeholder-",C=function(){},T=function(e){function t(){s(this,t);var n=l(this,e.apply(this,arguments));n.getInitAnimType=function(e,t){var n=c({},(0,h.assignChild)(t)),r=g&&g.prototype.constructor&&g.prototype.constructor.CSS.Lists.transformsBase||[],o=g&&g.prototype.constructor&&g.prototype.constructor.CSS.setPropertyValue||C,i=g&&g.prototype.constructor&&g.prototype.constructor.CSS.Values.getUnitType||C,a=e.style;return Object.keys(n).forEach(function(t){var s=t;if(r.indexOf(t)>=0){s="transform";var l=a[(0,h.checkStyleName)(s)];if(l&&"none"!==l&&l.match(t)){var u=new RegExp("^.*"+t+"\\(([^\\)]+?)\\).*","i"),c=l.replace(u,"$1");n[t][1]=parseFloat(c)}}else a[t]&&parseFloat(a[t])&&(n[t][1]=parseFloat(a[t]));o(e,s,""+n[t][1]+i(t))}),n},n.keysToEnter=[],n.keysToLeave=[],n.keysAnimating=[],n.placeholderTimeoutIds={};var r=(0,h.toArrayChildren)((0,h.getChildrenFromProps)(n.props));return r.forEach(function(e){e&&e.key&&n.keysToEnter.push(e.key)}),n.originalChildren=(0,h.toArrayChildren)((0,h.getChildrenFromProps)(n.props)),n.state={children:r,childrenShow:{}},["performEnter","performLeave","enterBegin","leaveComplete"].forEach(function(e){return n[e]=n[e].bind(n)}),n}return u(t,e),t.prototype.componentDidMount=function(){this.componentDidUpdate()},t.prototype.componentWillReceiveProps=function(e){var t=this,n=(0,h.toArrayChildren)(e.children),r=this.originalChildren,o=(0,h.mergeChildren)(r,n),i=o.length?this.state.childrenShow:{};this.keysToLeave.forEach(function(n){var r=(0,d.findDOMNode)(t.refs[n]);g(r,"stop"),e.enterForcedRePlay&&delete i[n]}),this.keysToEnter=[],this.keysToLeave=[],this.keysAnimating=[],this.setState({childrenShow:i,children:o}),n.forEach(function(e){if(e){var n=e.key,o=(0,h.findChildInChildrenByKey)(r,n);!o&&n&&t.keysToEnter.push(n)}}),r.forEach(function(e){if(e){var r=e.key,o=(0,h.findChildInChildrenByKey)(n,r);!o&&r&&t.keysToLeave.push(r)}})},t.prototype.componentDidUpdate=function(){this.originalChildren=(0,h.toArrayChildren)((0,h.getChildrenFromProps)(this.props));var e=Array.prototype.slice.call(this.keysToEnter),t=Array.prototype.slice.call(this.keysToLeave);0===this.keysAnimating.length&&(this.keysAnimating=e.concat(t)),e.forEach(this.performEnter),t.forEach(this.performLeave)},t.prototype.componentWillUnmount=function(){var e=this;[].concat(this.keysToEnter,this.keysToLeave,this.keysAnimating).forEach(function(t){return e.refs[t]&&g((0,d.findDOMNode)(e.refs[t]),"stop")}),Object.keys(this.placeholderTimeoutIds).forEach(function(t){clearTimeout(e.placeholderTimeoutIds[t])}),this.keysToEnter=[],this.keysToLeave=[],this.keysAnimating=[]},t.prototype.getVelocityConfig=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return this.props.animConfig?h.transformArguments.apply(void 0,[this.props.animConfig].concat(n))[e]:v["default"][h.transformArguments.apply(void 0,[this.props.type].concat(n))[e]]},t.prototype.getVelocityEnterConfig=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.getVelocityConfig.apply(this,[0].concat(t))},t.prototype.getVelocityLeaveConfig=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=this.getVelocityConfig.apply(this,[1].concat(t)),o={};return Object.keys(r).forEach(function(e){Array.isArray(r[e])?o[e]=Array.prototype.slice.call(r[e]).reverse():o[e]=r[e]}),o},t.prototype.getVelocityEasing=function(){ for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return h.transformArguments.apply(void 0,[this.props.ease].concat(t)).map(function(e){if("string"==typeof e)return b[e]||e})},t.prototype.performEnter=function(e,t){var n=(0,h.transformArguments)(this.props.interval,e,t)[0],r=(0,h.transformArguments)(this.props.delay,e,t)[0];this.placeholderTimeoutIds[e]=setTimeout(this.performEnterBegin.bind(this,e,t),n*t+r),this.keysToEnter.indexOf(e)>=0&&this.keysToEnter.splice(this.keysToEnter.indexOf(e),1)},t.prototype.performEnterBegin=function(e,t){var n=this.state.childrenShow;n[e]=!0,this.setState({childrenShow:n},this.realPerformEnter.bind(this,e,t))},t.prototype.realPerformEnter=function(e,t){var n=(0,d.findDOMNode)(this.refs[e]);if(n){var r=(0,h.transformArguments)(this.props.duration,e,t)[0];g(n,"stop");var o=this.props.enterForcedRePlay?this.getVelocityEnterConfig(e,t):this.getInitAnimType(n,this.getVelocityEnterConfig(e,t));this.props.enterForcedRePlay&&(n.style.visibility="hidden"),g(n,o,{duration:r,easing:this.getVelocityEasing(e,t)[0],visibility:"visible",begin:this.enterBegin.bind(this,e),complete:this.enterComplete.bind(this,e)})}},t.prototype.performLeave=function(e,t){clearTimeout(this.placeholderTimeoutIds[e]),delete this.placeholderTimeoutIds[e];var n=(0,d.findDOMNode)(this.refs[e]);if(n){var r=(0,h.transformArguments)(this.props.interval,e,t)[1],o=(0,h.transformArguments)(this.props.delay,e,t)[1],i=(0,h.transformArguments)(this.props.duration,e,t)[1],a=this.props.leaveReverse?this.keysToLeave.length-t-1:t;g(n,"stop"),n.style.visibility="visible";var s=this.getInitAnimType(n,this.getVelocityLeaveConfig(e,t));g(n,s,{delay:r*a+o,duration:i,easing:this.getVelocityEasing(e,t)[1],begin:this.leaveBegin.bind(this),complete:this.leaveComplete.bind(this,e)})}},t.prototype.enterBegin=function(e,t){var n=this;t.forEach(function(e){var t=n.props.animatingClassName;e.className=e.className.replace(t[1],""),e.className.indexOf(t[0])===-1&&(e.className+=" "+t[0])})},t.prototype.enterComplete=function(e,t){var n=this;this.keysAnimating.indexOf(e)>=0&&this.keysAnimating.splice(this.keysAnimating.indexOf(e),1),t.forEach(function(e){e.className=e.className.replace(n.props.animatingClassName[0],"").trim()})},t.prototype.leaveBegin=function(e){var t=this;e.forEach(function(e){var n=t.props.animatingClassName;e.className=e.className.replace(n[0],""),e.className.indexOf(n[1])===-1&&(e.className+=" "+n[1])})},t.prototype.leaveComplete=function(e,t){var n=this;if(!(this.keysAnimating.indexOf(e)<0)){this.keysAnimating.splice(this.keysAnimating.indexOf(e),1);var r=this.state.childrenShow;r[e]=!1,this.keysToLeave.indexOf(e)>=0&&this.keysToLeave.splice(this.keysToLeave.indexOf(e),1);var o=this.keysToLeave.some(function(e){return r[e]});if(!o){var i=(0,h.toArrayChildren)((0,h.getChildrenFromProps)(this.props));this.setState({children:i,childrenShow:r})}t.forEach(function(e){e.className=e.className.replace(n.props.animatingClassName[1],"").trim()})}},t.prototype.render=function(){var e=this,t=(0,h.toArrayChildren)(this.state.children).map(function(t){return t&&t.key?e.state.childrenShow[t.key]?(0,p.cloneElement)(t,{ref:t.key,key:t.key}):(0,p.createElement)("div",{ref:P+t.key,key:P+t.key}):t}),n=a(this.props,[]);return["component","interval","duration","delay","type","animConfig","ease","leaveReverse","animatingClassName","enterForcedRePlay"].forEach(function(e){return delete n[e]}),(0,p.createElement)(this.props.component,c({},n),t)},t}(f["default"].Component),O=f["default"].PropTypes.oneOfType([f["default"].PropTypes.number,f["default"].PropTypes.array]),w=f["default"].PropTypes.oneOfType([f["default"].PropTypes.string,f["default"].PropTypes.array]),x=f["default"].PropTypes.oneOfType([f["default"].PropTypes.object,f["default"].PropTypes.array]),E=f["default"].PropTypes.oneOfType([f["default"].PropTypes.func,f["default"].PropTypes.string]),S=f["default"].PropTypes.oneOfType([f["default"].PropTypes.func,w]),k=f["default"].PropTypes.oneOfType([f["default"].PropTypes.func,x]),N=f["default"].PropTypes.oneOfType([f["default"].PropTypes.func,O]);T.propTypes={component:E,interval:O,duration:N,delay:N,type:S,animConfig:k,ease:S,leaveReverse:f["default"].PropTypes.bool,enterForcedRePlay:f["default"].PropTypes.bool,animatingClassName:f["default"].PropTypes.array},T.defaultProps={component:"div",interval:100,duration:450,delay:0,type:"right",animConfig:null,ease:"easeOutQuart",leaveReverse:!1,enterForcedRePlay:!1,animatingClassName:["queue-anim-entering","queue-anim-leaving"]},t["default"]=T,e.exports=t["default"]}).call(t,n(84).setImmediate)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={left:{opacity:[1,0],translateX:[0,-30]},top:{opacity:[1,0],translateY:[0,-30]},right:{opacity:[1,0],translateX:[0,30]},bottom:{opacity:[1,0],translateY:[0,30]},alpha:{opacity:[1,0]},scale:{opacity:[1,0],scale:[1,0]},scaleBig:{opacity:[1,0],scale:[1,2]},scaleX:{opacity:[1,0],scaleX:[1,0]},scaleY:{opacity:[1,0],scaleY:[1,0]}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(437),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=[];return h["default"].Children.forEach(e,function(e){t.push(e)}),t}function i(e,t){var n=null;return e&&e.forEach(function(e){!n&&e&&e.key===t&&(n=e)}),n}function a(e,t){var n=[],r={},o=[],a=void 0;return e.forEach(function(e){e&&(i(t,e.key)?(o.length&&(r[e.key]=o,o=[]),a=e.key):e.key&&o.push(e))}),a||(n=n.concat(o)),t.forEach(function(e){e&&(r.hasOwnProperty(e.key)&&(n=n.concat(r[e.key])),n.push(e),e.key===a&&(n=n.concat(o)))}),n}function s(e,t,n){var r=void 0;return r="function"==typeof e?e({key:t,index:n}):e,Array.isArray(r)&&2===r.length?r:[r,r]}function l(e){return e&&e.children}function u(e){var t={};return Object.keys(e).forEach(function(n){return Array.isArray(e[n])?void(t[n]=[].concat(e[n])):"object"===f(e[n])?void(t[n]=p({},e[n])):void(t[n]=e[n])}),t}function c(e){var t=["O","Moz","ms","Ms","Webkit"];if("filter"!==e&&e in document.body.style)return e;var n=e.charAt(0).toUpperCase()+e.substr(1);return""+(t.filter(function(e){return""+e+n in document.body.style})[0]||"")+n}Object.defineProperty(t,"__esModule",{value:!0});var p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f="function"==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.toArrayChildren=o,t.findChildInChildrenByKey=i,t.mergeChildren=a,t.transformArguments=s,t.getChildrenFromProps=l,t.assignChild=u,t.checkStyleName=c;var d=n(1),h=r(d)},function(e,t,n){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(1),i=n(149),a=o.createClass({displayName:"Radio",getDefaultProps:function(){return{prefixCls:"rc-radio",type:"radio"}},render:function(){return o.createElement(i,r({},this.props,{ref:"checkbox"}))}});e.exports=a},function(e,t,n){"use strict";e.exports=n(441)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var i=n(4),a=r(i),s=n(1),l=r(s),u=n(446),c=n(444),p=r(c),f=l["default"].createClass({displayName:"Rate",propTypes:{disabled:s.PropTypes.bool,value:s.PropTypes.number,defaultValue:s.PropTypes.number,count:s.PropTypes.number,allowHalf:s.PropTypes.bool,style:s.PropTypes.object,prefixCls:s.PropTypes.string,onChange:s.PropTypes.func},getDefaultProps:function(){return{defaultValue:0,count:5,allowHalf:!1,style:{},prefixCls:"rc-rate",onChange:o}},getInitialState:function(){var e=this.props.value;return void 0===e&&(e=this.props.defaultValue),{value:e}},componentWillReceiveProps:function(e){if("value"in e){var t=e.value;void 0===t&&(t=e.defaultValue),this.setState({value:t})}},onHover:function(e,t){var n=this.getStarValue(t,e.pageX);this.setState({hoverValue:n})},onMouseLeave:function(){this.setState({hoverValue:void 0})},onClick:function(e,t){var n=this.getStarValue(t,e.pageX);"value"in this.props||this.setState({value:n}),this.onMouseLeave(),this.props.onChange(n)},getStarDOM:function(e){return a["default"].findDOMNode(this.refs["star_"+e])},getStarValue:function(e,t){var n=e+1;if(this.props.allowHalf){var r=(0,u.getOffsetLeft)(this.getStarDOM(0)),o=(0,u.getOffsetLeft)(this.getStarDOM(1))-r;t-r-o*e<o/2&&(n-=.5)}return n},render:function(){for(var e=this.props,t=e.count,n=e.allowHalf,r=e.style,o=e.prefixCls,i=e.disabled,a=this.state,s=a.value,u=a.hoverValue,c=[],f=i?o+"-disabled":"",d=0;d<t;d++)c.push(l["default"].createElement(p["default"],{ref:"star_"+d,index:d,disabled:i,prefixCls:o+"-star",allowHalf:n,value:void 0===u?s:u,onClick:this.onClick,onHover:this.onHover,key:d}));return l["default"].createElement("ul",{className:o+" "+f,style:r,onMouseLeave:i?null:this.onMouseLeave},c)}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=i["default"].createClass({displayName:"Star",propTypes:{value:o.PropTypes.number,index:o.PropTypes.number,prefixCls:o.PropTypes.string,allowHalf:o.PropTypes.bool,disabled:o.PropTypes.bool,onHover:o.PropTypes.func,onClick:o.PropTypes.func},onHover:function(e){this.props.onHover(e,this.props.index)},onClick:function(e){this.props.onClick(e,this.props.index)},getClassName:function(){var e=this.props,t=e.index,n=e.value,r=e.prefixCls,o=e.allowHalf,i=t+1;return o&&n+.5===i?r+" "+r+"-half "+r+"-active":i<=n?r+" "+r+"-full":r+" "+r+"-zero"},render:function(){var e=this.onHover,t=this.onClick,n=this.props,r=n.disabled,o=n.prefixCls;return i["default"].createElement("li",{className:this.getClassName(),onClick:r?null:t,onMouseMove:r?null:e},i["default"].createElement("div",{className:o+"-content"}))}});t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(443),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=t?e.pageYOffset:e.pageXOffset,r=t?"scrollTop":"scrollLeft";if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function r(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,i=o.body,a=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=a.clientLeft||i.clientLeft||0,r-=a.clientTop||i.clientTop||0,{left:n,top:r}}function o(e){var t=r(e),o=e.ownerDocument,i=o.defaultView||o.parentWindow;return t.left+=n(i),t.left}Object.defineProperty(t,"__esModule",{value:!0}),t.getOffsetLeft=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(49),i=r(o),a=n(7),s=r(a),l=n(1),u=r(l),c=n(4),p=n(56),f=n(40),d=r(f),h=n(78),y=r(h),v=u["default"].createClass({displayName:"DropdownMenu",propTypes:{defaultActiveFirstOption:l.PropTypes.bool,value:l.PropTypes.any,dropdownMenuStyle:l.PropTypes.object,multiple:l.PropTypes.bool,onPopupFocus:l.PropTypes.func,onMenuDeSelect:l.PropTypes.func,onMenuSelect:l.PropTypes.func,prefixCls:l.PropTypes.string,menuItems:l.PropTypes.any,inputValue:l.PropTypes.string,visible:l.PropTypes.bool},componentWillMount:function(){this.lastInputValue=this.props.inputValue},componentDidMount:function(){this.scrollActiveItemToView(),this.lastVisible=this.props.visible},shouldComponentUpdate:function(e){return e.visible||(this.lastVisible=!1),e.visible},componentDidUpdate:function(e){var t=this.props;!e.visible&&t.visible&&this.scrollActiveItemToView(),this.lastVisible=t.visible,this.lastInputValue=t.inputValue},scrollActiveItemToView:function(){var e=(0,c.findDOMNode)(this.firstActiveItem);e&&(0,y["default"])(e,(0,c.findDOMNode)(this.refs.menu),{onlyScrollIfNeeded:!0})},renderMenu:function(){var e=this,t=this.props,n=t.menuItems,r=t.defaultActiveFirstOption,o=t.value,a=t.prefixCls,c=t.multiple,h=t.onMenuSelect,y=t.inputValue;if(n&&n.length){var v=function(){var i={};c?(i.onDeselect=t.onMenuDeselect,i.onSelect=h):i.onClick=h;var v=(0,p.getSelectKeys)(n,o),m={},g=n;return v.length&&!function(){t.visible&&!e.lastVisible&&(m.activeKey=v[0]);var r=!1,o=function(t){return r||v.indexOf(t.key)===-1?t:(r=!0,(0,l.cloneElement)(t,{ref:function(t){e.firstActiveItem=t}}))};g=n.map(function(e){if(e.type===f.ItemGroup){var t=e.props.children.map(o);return(0,l.cloneElement)(e,{},t)}return o(e)})}(),y!==e.lastInputValue&&(m.activeKey=""),{v:u["default"].createElement(d["default"],(0,s["default"])({ref:"menu",style:e.props.dropdownMenuStyle,defaultActiveFirst:r},m,{multiple:c,focusable:!1},i,{selectedKeys:v,prefixCls:a+"-menu"}),g)}}();if("object"===("undefined"==typeof v?"undefined":(0,i["default"])(v)))return v.v}return null},render:function(){return u["default"].createElement("div",{style:{overflow:"auto"},onFocus:this.props.onPopupFocus,onMouseDown:p.preventDefaultEvent},this.renderMenu())}});t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(7),i=r(o),a=n(1),s=r(a),l=n(56),u=n(40),c=n(452),p=r(c),f=n(82),d=r(f),h=n(156),y=r(h);t["default"]={filterOption:function v(e,t){if(!e)return!0;var v=this.props.filterOption;return!v||!t.props.disabled&&v.call(this,e,t)},renderFilterOptions:function(e){return this.renderFilterOptionsFromChildren(this.props.children,!0,e)},renderFilterOptionsFromChildren:function(e,t,n){var r=this,o=[],a=this.props,c=void 0===n?this.state.inputValue:n,f=[],h=a.tags;if(s["default"].Children.forEach(e,function(e){if(e.type!==d["default"]){(0,p["default"])(e.type===y["default"],"the children of `Select` should be `Select.Option` or `Select.OptGroup`, "+("instead of `"+(e.type.name||e.type.displayName||e.type)+"`."));var t=(0,l.getValuePropValue)(e);r.filterOption(c,e)&&o.push(s["default"].createElement(u.Item,(0,i["default"])({style:l.UNSELECTABLE_STYLE,attribute:l.UNSELECTABLE_ATTRIBUTE,value:t,key:t},e.props))),h&&!e.props.disabled&&f.push(t)}else{var n=r.renderFilterOptionsFromChildren(e.props.children,!1);if(n.length){var a=e.props.label,v=e.key;v||"string"!=typeof a?!a&&v&&(a=v):v=a,o.push(s["default"].createElement(u.ItemGroup,{key:v,title:a},n))}}}),h){var v=this.state.value||[];if(v=v.filter(function(e){return f.indexOf(e.key)===-1&&(!c||String(e.key).indexOf(String(c))>-1)}),o=o.concat(v.map(function(e){var t=e.key;return s["default"].createElement(u.Item,{style:l.UNSELECTABLE_STYLE,attribute:l.UNSELECTABLE_ATTRIBUTE,value:t,key:t},t)})),c){var m=o.every(function(e){return(0,l.getValuePropValue)(e)!==c});m&&o.unshift(s["default"].createElement(u.Item,{style:l.UNSELECTABLE_STYLE,attribute:l.UNSELECTABLE_ATTRIBUTE,value:c,key:c},c))}}return!o.length&&t&&a.notFoundContent&&(o=[s["default"].createElement(u.Item,{style:l.UNSELECTABLE_STYLE,attribute:l.UNSELECTABLE_ATTRIBUTE,disabled:!0,value:"NOT_FOUND",key:"NOT_FOUND"},a.notFoundContent)]),o}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e,t){return String((0,x.getPropValue)(t,this.props.optionFilterProp)).indexOf(e)>-1}function a(e,t){this[e]=t}Object.defineProperty(t,"__esModule",{value:!0});var s=n(12),l=r(s),u=n(7),c=r(u),p=n(1),f=r(p),d=n(4),h=r(d),y=n(15),v=r(y),m=n(2),g=r(m),b=n(82),P=r(b),C=n(9),T=r(C),O=n(118),w=r(O),x=n(56),E=n(450),S=r(E),k=n(448),N=r(k),j=void 0;p.PropTypes&&(j=p.PropTypes.oneOfType([p.PropTypes.string,p.PropTypes.shape({key:p.PropTypes.string,label:p.PropTypes.node})]));var _=f["default"].createClass({displayName:"Select",propTypes:{defaultActiveFirstOption:p.PropTypes.bool,multiple:p.PropTypes.bool,filterOption:p.PropTypes.any,showSearch:p.PropTypes.bool,disabled:p.PropTypes.bool,allowClear:p.PropTypes.bool,showArrow:p.PropTypes.bool,tags:p.PropTypes.bool,prefixCls:p.PropTypes.string,className:p.PropTypes.string,transitionName:p.PropTypes.string,optionLabelProp:p.PropTypes.string,optionFilterProp:p.PropTypes.string,animation:p.PropTypes.string,choiceTransitionName:p.PropTypes.string,onChange:p.PropTypes.func,onBlur:p.PropTypes.func,onSelect:p.PropTypes.func,onSearch:p.PropTypes.func,placeholder:p.PropTypes.any,onDeselect:p.PropTypes.func,labelInValue:p.PropTypes.bool,value:p.PropTypes.oneOfType([j,p.PropTypes.arrayOf(j)]),defaultValue:p.PropTypes.oneOfType([j,p.PropTypes.arrayOf(j)]),dropdownStyle:p.PropTypes.object,maxTagTextLength:p.PropTypes.number},mixins:[N["default"]],getDefaultProps:function(){return{prefixCls:"rc-select",filterOption:i,defaultOpen:!1,labelInValue:!1,defaultActiveFirstOption:!0,showSearch:!0,allowClear:!1,placeholder:"",defaultValue:[],onChange:o,onBlur:o,onSelect:o,onSearch:o,onDeselect:o,showArrow:!0,dropdownMatchSelectWidth:!0,dropdownStyle:{},dropdownMenuStyle:{},optionFilterProp:"value",optionLabelProp:"value",notFoundContent:"Not Found"}},getInitialState:function(){var e=this.props,t=[];t="value"in e?(0,x.toArray)(e.value):(0,x.toArray)(e.defaultValue),t=this.addLabelToValue(e,t);var n="";e.combobox&&(n=t.length?String(t[0].key):""),this.saveInputRef=a.bind(this,"inputInstance"),this.saveInputMirrorRef=a.bind(this,"inputMirrorInstance");var r=e.open;return void 0===r&&(r=e.defaultOpen),{value:t,inputValue:n,open:r}},componentWillReceiveProps:function(e){if("value"in e){var t=(0,x.toArray)(e.value);t=this.addLabelToValue(e,t),this.setState({value:t}),e.combobox&&this.setState({inputValue:t.length?String(t[0].key):""})}},componentDidUpdate:function(){var e=this.state,t=this.props;if(e.open&&(0,x.isMultipleOrTags)(t)){var n=this.getInputDOMNode(),r=this.getInputMirrorDOMNode();n.value?(n.style.width="",n.style.width=r.clientWidth+"px"):n.style.width=""}},componentWillUnmount:function(){this.clearBlurTime(),this.dropdownContainer&&(h["default"].unmountComponentAtNode(this.dropdownContainer),document.body.removeChild(this.dropdownContainer),this.dropdownContainer=null)},onInputChange:function(e){var t=e.target.value,n=this.props;this.setInputValue(t),this.setState({open:!0}),(0,x.isCombobox)(n)&&this.fireChange([{key:t}])},onDropdownVisibleChange:function(e){this.setOpenState(e)},onKeyDown:function(e){var t=this.props;if(!t.disabled){var n=e.keyCode;this.state.open&&!this.getInputDOMNode()?this.onInputKeyDown(e):n!==v["default"].ENTER&&n!==v["default"].DOWN||(this.setOpenState(!0),e.preventDefault())}},onInputKeyDown:function(e){var t=this.props;if(!t.disabled){var n=this.state,r=e.keyCode;if(!(0,x.isMultipleOrTags)(t)||e.target.value||r!==v["default"].BACKSPACE){if(r===v["default"].DOWN){if(!n.open)return this.openIfHasChildren(),e.preventDefault(),void e.stopPropagation()}else if(r===v["default"].ESC)return void(n.open&&(this.setOpenState(!1),e.preventDefault(),e.stopPropagation()));if(n.open){var o=this.refs.trigger.getInnerMenu();o&&o.onKeyDown(e)&&(e.preventDefault(),e.stopPropagation())}}else{e.preventDefault();var i=n.value.concat();if(i.length){var a=i.pop();t.onDeselect(t.labelInValue?a:a.key),this.fireChange(i)}}}},onMenuSelect:function(e){var t=e.item,n=this.state.value,r=this.props,o=(0,x.getValuePropValue)(t),i=this.getLabelFromOption(t),a=o;if(r.labelInValue&&(a={key:a,label:i}),r.onSelect(a,t),(0,x.isMultipleOrTags)(r)){if((0,x.findIndexInValueByKey)(n,o)!==-1)return;n=n.concat([{key:o,label:i}])}else{if(n.length&&n[0].key===o)return void this.setOpenState(!1,!0);n=[{key:o,label:i}],this.setOpenState(!1,!0)}this.fireChange(n);var s=void 0;s=(0,x.isCombobox)(r)?(0,x.getPropValue)(t,r.optionLabelProp):"",this.setInputValue(s,!1)},onMenuDeselect:function(e){var t=e.item,n=e.domEvent;"click"===n.type&&this.removeSelected((0,x.getValuePropValue)(t)),this.setInputValue("",!1)},onArrowClick:function(e){e.stopPropagation(),this.props.disabled||this.setOpenState(!this.state.open,!0)},onPlaceholderClick:function(){this.getInputDOMNode()&&this.getInputDOMNode().focus()},onOuterFocus:function(){this.clearBlurTime(),this._focused=!0,this.updateFocusClassName()},onPopupFocus:function(){this.maybeFocus(!0,!0)},onOuterBlur:function(){var e=this;this.blurTimer=setTimeout(function(){e._focused=!1,e.updateFocusClassName();var t=e.props,n=e.state.value,r=e.state.inputValue;if((0,x.isSingleMode)(t)&&t.showSearch&&r&&t.defaultActiveFirstOption){var o=e._options||[];if(o.length){var i=(0,x.findFirstMenuItem)(o);i&&(n=[{key:i.key,label:e.getLabelFromOption(i)}],e.fireChange(n))}}else(0,x.isMultipleOrTags)(t)&&r&&(e.state.inputValue=e.getInputDOMNode().value="");t.onBlur(e.getVLForOnChange(n))},10)},onClearSelection:function(e){var t=this.props,n=this.state;if(!t.disabled){var r=n.inputValue,o=n.value;e.stopPropagation(),(r||o.length)&&(o.length&&this.fireChange([]),this.setOpenState(!1,!0),r&&this.setInputValue(""))}},onChoiceAnimationLeave:function(){this.refs.trigger.refs.trigger.forcePopupAlign()},getLabelBySingleValue:function(e,t){var n=this;if(void 0===t)return null;var r=null;return f["default"].Children.forEach(e,function(e){if(e.type===P["default"]){var o=n.getLabelBySingleValue(e.props.children,t);null!==o&&(r=o)}else(0,x.getValuePropValue)(e)===t&&(r=n.getLabelFromOption(e))}),r},getLabelFromOption:function(e){return(0,x.getPropValue)(e,this.props.optionLabelProp)},getLabelFromProps:function(e,t){return this.getLabelByValue(e.children,t)},getVLForOnChange:function(e){var t=e;return void 0!==t?(this.props.labelInValue||(t=t.map(function(e){return e.key})),(0,x.isMultipleOrTags)(this.props)?t:t[0]):t},getLabelByValue:function(e,t){var n=this.getLabelBySingleValue(e,t);return null===n?t:n},getDropdownContainer:function(){return this.dropdownContainer||(this.dropdownContainer=document.createElement("div"),document.body.appendChild(this.dropdownContainer)),this.dropdownContainer},getPlaceholderElement:function(){var e=this.props,t=this.state,n=!1;t.inputValue&&(n=!0),t.value.length&&(n=!0),(0,x.isCombobox)(e)&&1===t.value.length&&!t.value[0].key&&(n=!1);var r=e.placeholder;return r?f["default"].createElement("div",(0,c["default"])({onMouseDown:x.preventDefaultEvent,style:(0,c["default"])({display:n?"none":"block"},x.UNSELECTABLE_STYLE)},x.UNSELECTABLE_ATTRIBUTE,{onClick:this.onPlaceholderClick,className:e.prefixCls+"-selection__placeholder"}),r):null},getInputElement:function(){var e=this.props;return f["default"].createElement("div",{className:e.prefixCls+"-search__field__wrap"},f["default"].createElement("input",{ref:this.saveInputRef,onChange:this.onInputChange,onKeyDown:this.onInputKeyDown,value:this.state.inputValue,disabled:e.disabled,className:e.prefixCls+"-search__field"}),f["default"].createElement("span",{ref:this.saveInputMirrorRef,className:e.prefixCls+"-search__field__mirror"},this.state.inputValue))},getInputDOMNode:function(){return this.inputInstance},getInputMirrorDOMNode:function(){return this.inputMirrorInstance},getPopupDOMNode:function(){return this.refs.trigger.getPopupDOMNode()},getPopupMenuComponent:function(){return this.refs.trigger.getInnerMenu()},setOpenState:function(e,t){var n=this,r=this.props,o=this.state;if(o.open===e)return void this.maybeFocus(e,t);var i={open:e};!e&&(0,x.isSingleMode)(r)&&r.showSearch&&this.setInputValue(""),e||this.maybeFocus(e,t),this.setState(i,function(){e&&n.maybeFocus(e,t)})},setInputValue:function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];this.setState({inputValue:e}),t&&this.props.onSearch(e)},clearBlurTime:function(){this.blurTimer&&(clearTimeout(this.blurTimer),this.blurTimer=null)},updateFocusClassName:function(){var e=this.refs,t=this.props;this._focused?(0,w["default"])(e.root).add(t.prefixCls+"-focused"):(0,w["default"])(e.root).remove(t.prefixCls+"-focused")},maybeFocus:function(e,t){if(t||e){var n=this.getInputDOMNode(),r=document,o=r.activeElement;if(n&&(e||(0,x.isMultipleOrTagsOrCombobox)(this.props)))o!==n&&n.focus();else{var i=this.refs.selection;o!==i&&i.focus()}}},addLabelToValue:function(e,t){var n=this,r=t;return e.labelInValue?r.forEach(function(t){t.label=t.label||n.getLabelFromProps(e,t.key)}):r=r.map(function(t){return{key:t,label:n.getLabelFromProps(e,t)}}),r},removeSelected:function(e){var t=this.props;if(!t.disabled){var n=void 0,r=this.state.value.filter(function(t){return t.key===e&&(n=t.label),t.key!==e}),o=(0,x.isMultipleOrTags)(t);if(o){var i=e;t.labelInValue&&(i={key:e,label:n}),t.onDeselect(i)}this.fireChange(r)}},openIfHasChildren:function(){var e=this.props;(f["default"].Children.count(e.children)||(0,x.isSingleMode)(e))&&this.setOpenState(!0)},fireChange:function(e){var t=this.props;"value"in t||this.setState({value:e}),t.onChange(this.getVLForOnChange(e))},renderTopControlNode:function(){var e=this,t=this.state,n=t.value,r=t.open,o=t.inputValue,i=this.props,a=i.choiceTransitionName,s=i.prefixCls,l=i.maxTagTextLength,u=i.showSearch,p=s+"-selection__rendered",d=null;if((0,x.isSingleMode)(i)){var h=null;if(n.length){var y=!1,v=1;u&&r?(y=!o,y&&(v=.4)):y=!0,h=f["default"].createElement("div",{key:"value",className:s+"-selection-selected-value",title:n[0].label,style:{display:y?"block":"none",opacity:v}},n[0].label)}d=u?[h,f["default"].createElement("div",{className:s+"-search "+s+"-search--inline",key:"input",style:{display:r?"block":"none"}},this.getInputElement())]:[h]}else{var m=[];(0,x.isMultipleOrTags)(i)&&(m=n.map(function(t){var n=t.label,r=n;l&&"string"==typeof n&&n.length>l&&(n=n.slice(0,l)+"...");var o=(0,x.toArray)(i.children).some(function(e){var n=(0,x.getValuePropValue)(e);return n===t.key&&e.props&&e.props.disabled}),a=o?s+"-selection__choice "+s+"-selection__choice__disabled":s+"-selection__choice";return f["default"].createElement("li",(0,c["default"])({style:x.UNSELECTABLE_STYLE},x.UNSELECTABLE_ATTRIBUTE,{onMouseDown:x.preventDefaultEvent,className:a,key:t.key,title:r}),f["default"].createElement("div",{className:s+"-selection__choice__content"},n),o?null:f["default"].createElement("span",{className:s+"-selection__choice__remove",onClick:e.removeSelected.bind(e,t.key)}))})),m.push(f["default"].createElement("li",{className:s+"-search "+s+"-search--inline",key:"__input"},this.getInputElement())),d=(0,x.isMultipleOrTags)(i)&&a?f["default"].createElement(T["default"],{onLeave:this.onChoiceAnimationLeave,component:"ul",transitionName:a},m):f["default"].createElement("ul",null,m)}return f["default"].createElement("div",{className:p},this.getPlaceholderElement(),d)},render:function(){var e,t=this.props,n=(0,x.isMultipleOrTags)(t),r=this.state,o=t.className,i=t.disabled,a=t.allowClear,s=t.prefixCls,u=this.renderTopControlNode(),p={},d=this.state.open,h=[];d&&(h=this.renderFilterOptions()),this._options=h,!d||!(0,x.isMultipleOrTagsOrCombobox)(t)&&t.showSearch||h.length||(d=!1),(0,x.isMultipleOrTagsOrCombobox)(t)||(p={onKeyDown:this.onKeyDown,tabIndex:0});var y=(e={},(0,l["default"])(e,o,!!o),(0,l["default"])(e,s,1),(0,l["default"])(e,s+"-open",d),(0,l["default"])(e,s+"-focused",d||!!this._focused),(0,l["default"])(e,s+"-combobox",(0,x.isCombobox)(t)),(0,l["default"])(e,s+"-disabled",i),(0,l["default"])(e,s+"-enabled",!i),(0,l["default"])(e,s+"-allow-clear",!!t.allowClear),e),v=(0,c["default"])({},x.UNSELECTABLE_STYLE,{display:"none"});(r.inputValue||r.value.length)&&(v.display="block");var m=f["default"].createElement("span",(0,c["default"])({key:"clear",onMouseDown:x.preventDefaultEvent,style:v},x.UNSELECTABLE_ATTRIBUTE,{className:s+"-selection__clear",onClick:this.onClearSelection}));return f["default"].createElement(S["default"],{onPopupFocus:this.onPopupFocus,dropdownAlign:t.dropdownAlign,dropdownClassName:t.dropdownClassName,dropdownMatchSelectWidth:t.dropdownMatchSelectWidth,defaultActiveFirstOption:t.defaultActiveFirstOption,dropdownMenuStyle:t.dropdownMenuStyle,transitionName:t.transitionName,animation:t.animation,prefixCls:t.prefixCls,dropdownStyle:t.dropdownStyle,combobox:t.combobox,showSearch:t.showSearch,options:h,multiple:n,disabled:i,visible:d,inputValue:r.inputValue,value:r.value,onDropdownVisibleChange:this.onDropdownVisibleChange,getPopupContainer:t.getPopupContainer,onMenuSelect:this.onMenuSelect,onMenuDeselect:this.onMenuDeselect,ref:"trigger"},f["default"].createElement("div",{style:t.style,ref:"root",onBlur:this.onOuterBlur,onFocus:this.onOuterFocus,className:(0,g["default"])(y)},f["default"].createElement("div",(0,c["default"])({ref:"selection",key:"selection",className:s+"-selection\n "+s+"-selection--"+(n?"multiple":"single"),role:"combobox","aria-autocomplete":"list","aria-haspopup":"true","aria-expanded":d},p),u,a&&!n?m:null,n||!t.showArrow?null:f["default"].createElement("span",(0,c["default"])({key:"arrow",className:s+"-arrow",style:x.UNSELECTABLE_STYLE},x.UNSELECTABLE_ATTRIBUTE,{onMouseDown:x.preventDefaultEvent,onClick:this.onArrowClick}),f["default"].createElement("b",null)))))}});t["default"]=_,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(12),i=r(o),a=n(117),s=r(a),l=n(7),u=r(l),c=n(28),p=r(c),f=n(1),d=r(f),h=n(2),y=r(h),v=n(447),m=r(v),g=n(4),b=r(g),P=n(56),C={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:0,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:0,adjustY:1}}},T=d["default"].createClass({displayName:"SelectTrigger",propTypes:{onPopupFocus:f.PropTypes.func,dropdownMatchSelectWidth:f.PropTypes.bool,dropdownAlign:f.PropTypes.object,visible:f.PropTypes.bool,disabled:f.PropTypes.bool,showSearch:f.PropTypes.bool,dropdownClassName:f.PropTypes.string,multiple:f.PropTypes.bool,inputValue:f.PropTypes.string,filterOption:f.PropTypes.any,options:f.PropTypes.any,prefixCls:f.PropTypes.string,popupClassName:f.PropTypes.string,children:f.PropTypes.any},componentDidUpdate:function(){var e=this.props,t=e.visible,n=e.dropdownMatchSelectWidth;if(t){var r=this.getPopupDOMNode();if(r){var o=n?"width":"minWidth";r.style[o]=b["default"].findDOMNode(this).offsetWidth+"px"}}},getInnerMenu:function(){return this.popupMenu&&this.popupMenu.refs.menu},getPopupDOMNode:function(){return this.refs.trigger.getPopupDomNode()},getDropdownElement:function(e){var t=this.props;return d["default"].createElement(m["default"],(0,u["default"])({ref:this.saveMenu},e,{prefixCls:this.getDropdownPrefixCls(),onMenuSelect:t.onMenuSelect,onMenuDeselect:t.onMenuDeselect,value:t.value,defaultActiveFirstOption:t.defaultActiveFirstOption,dropdownMenuStyle:t.dropdownMenuStyle}))},getDropdownTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=this.getDropdownPrefixCls()+"-"+e.animation),t},getDropdownPrefixCls:function(){return this.props.prefixCls+"-dropdown"},saveMenu:function(e){this.popupMenu=e},render:function(){var e,t=this.props,n=t.onPopupFocus,r=(0,s["default"])(t,["onPopupFocus"]),o=r.multiple,a=r.visible,l=r.inputValue,c=r.dropdownAlign,f=r.disabled,h=r.showSearch,v=r.dropdownClassName,m=this.getDropdownPrefixCls(),g=(e={},(0,i["default"])(e,v,!!v),(0,i["default"])(e,m+"--"+(o?"multiple":"single"),1),e),b=this.getDropdownElement({menuItems:r.options,onPopupFocus:n,multiple:o,inputValue:l,visible:a}),T=void 0;return T=f?[]:(0,P.isSingleMode)(r)&&!h?["click"]:["blur"],d["default"].createElement(p["default"],(0,u["default"])({},r,{showAction:f?[]:["click"],hideAction:T,ref:"trigger",popupPlacement:"bottomLeft",builtinPlacements:C,prefixCls:m,popupTransitionName:this.getDropdownTransitionName(),onPopupVisibleChange:r.onDropdownVisibleChange,popup:b,popupAlign:c,popupVisible:a,getPopupContainer:r.getPopupContainer,popupClassName:(0,y["default"])(g),popupStyle:r.dropdownStyle}),r.children); }});t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.OptGroup=t.Option=void 0;var o=n(449),i=r(o),a=n(156),s=r(a),l=n(82),u=r(l);i["default"].Option=s["default"],i["default"].OptGroup=u["default"],t.Option=s["default"],t.OptGroup=u["default"],t["default"]=i["default"]},22,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(46),i=r(o),a=n(48),s=r(a),l=n(47),u=r(l),c=n(1),p=r(c),f=n(162),d=r(f),h=function(e){function t(n){(0,i["default"])(this,t);var r=(0,s["default"])(this,e.call(this,n));return r.state={isTooltipVisible:!1},r}return(0,u["default"])(t,e),t.prototype.showTooltip=function(){this.setState({isTooltipVisible:!0})},t.prototype.hideTooltip=function(){this.setState({isTooltipVisible:!1})},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.tipTransitionName,o=e.tipFormatter,i=e.vertical,a=e.offset,s=e.value,l=e.dragging,u=e.noTip,c=i?{bottom:a+"%"}:{left:a+"%"},f=p["default"].createElement("div",{className:n,style:c,onMouseUp:this.showTooltip.bind(this),onMouseEnter:this.showTooltip.bind(this),onMouseLeave:this.hideTooltip.bind(this)});if(u)return f;var h=l||this.state.isTooltipVisible;return p["default"].createElement(d["default"],{prefixCls:t.replace("slider","tooltip"),placement:"top",visible:h,overlay:p["default"].createElement("span",null,o(s)),delay:0,transitionName:r},f)},t}(p["default"].Component);t["default"]=h,h.propTypes={prefixCls:p["default"].PropTypes.string,className:p["default"].PropTypes.string,vertical:p["default"].PropTypes.bool,offset:p["default"].PropTypes.number,tipTransitionName:p["default"].PropTypes.string,tipFormatter:p["default"].PropTypes.func,value:p["default"].PropTypes.number,dragging:p["default"].PropTypes.bool,noTip:p["default"].PropTypes.bool},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(7),i=r(o),a=n(49),s=r(a),l=n(12),u=r(l),c=n(1),p=r(c),f=n(2),d=r(f),h=function(e){var t=e.className,n=e.vertical,r=e.marks,o=e.included,a=e.upperBound,l=e.lowerBound,c=e.max,f=e.min,h=Object.keys(r),y=h.length,v=100/(y-1),m=.9*v,g=c-f,b=h.map(parseFloat).sort(function(e,t){return e-t}).map(function(e){var c,h=!o&&e===a||o&&e<=a&&e>=l,y=(0,d["default"])((c={},(0,u["default"])(c,t+"-text",!0),(0,u["default"])(c,t+"-text-active",h),c)),v={marginBottom:"-200%",bottom:(e-f)/g*100+"%"},b={width:m+"%",marginLeft:-m/2+"%",left:(e-f)/g*100+"%"},P=n?v:b,C=r[e],T="object"===("undefined"==typeof C?"undefined":(0,s["default"])(C))&&!p["default"].isValidElement(C),O=T?C.label:C,w=T?(0,i["default"])({},P,C.style):P;return p["default"].createElement("span",{className:y,style:w,key:e},O)});return p["default"].createElement("div",{className:t},b)};t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e){return e.touches.length>1||"touchend"===e.type.toLowerCase()&&e.touches.length>0}function a(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function s(e,t){return e?t.clientY:t.pageX}function l(e){e.stopPropagation(),e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var u=n(12),c=r(u),p=n(314),f=r(p),d=n(7),h=r(d),y=n(46),v=r(y),m=n(48),g=r(m),b=n(47),P=r(b),C=n(1),T=r(C),O=n(20),w=r(O),x=n(2),E=r(x),S=n(457),k=r(S),N=n(453),j=r(N),_=n(456),M=r(_),D=n(454),A=r(D),L=function(e){function t(n){(0,v["default"])(this,t);var r=(0,g["default"])(this,e.call(this,n)),o=n.range,i=n.min,a=n.max,s=o?Array.apply(null,Array(o+1)).map(function(){return i}):i,l="defaultValue"in n?n.defaultValue:s,u=void 0!==n.value?n.value:l,c=(o?u:[i,u]).map(function(e){return r.trimAlignValue(e)}),p=void 0;return p=o&&c[0]===c[c.length-1]&&c[0]===a?0:c.length-1,r.state={handle:null,recent:p,bounds:c},r}return(0,P["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){var t=this;if("value"in e||"min"in e||"max"in e){var n=this.state.bounds;if(e.range){var r=e.value||n,o=r.map(function(n){return t.trimAlignValue(n,e)});if(o.every(function(e,t){return e===n[t]}))return;this.setState({bounds:o}),n.some(function(n){return t.isValueOutOfBounds(n,e)})&&this.props.onChange(o)}else{var i=void 0!==e.value?e.value:n[1],a=this.trimAlignValue(i,e);if(a===n[1]&&n[0]===e.min)return;this.setState({bounds:[e.min,a]}),this.isValueOutOfBounds(n[1],e)&&this.props.onChange(a)}}},t.prototype.onChange=function(e){var t=this.props,n=!("value"in t);n?this.setState(e):e.handle&&this.setState({handle:e.handle});var r=(0,h["default"])({},this.state,e),o=t.range?r.bounds:r.bounds[1];t.onChange(o)},t.prototype.onMouseMove=function(e){var t=s(this.props.vertical,e);this.onMove(e,t)},t.prototype.onTouchMove=function(e){if(i(e))return void this.end("touch");var t=a(this.props.vertical,e);this.onMove(e,t)},t.prototype.onMove=function(e,t){l(e);var n=this.props,r=this.state,o=t-this.startPosition;o=this.props.vertical?-o:o;var i=o/this.getSliderLength()*(n.max-n.min),a=this.trimAlignValue(this.startValue+i),s=r[r.handle];if(a!==s){var u=[].concat((0,f["default"])(r.bounds));u[r.handle]=a;var c=r.handle;if(n.pushable!==!1){var p=r.bounds[c];this.pushSurroundingHandles(u,c,p)}else n.allowCross&&(u.sort(function(e,t){return e-t}),c=u.indexOf(a));this.onChange({handle:c,bounds:u})}},t.prototype.onTouchStart=function(e){if(!i(e)){var t=a(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("touch"),l(e)}},t.prototype.onMouseDown=function(e){if(0===e.button){var t=s(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("mouse"),l(e)}},t.prototype.onStart=function(e){var t=this.props;t.onBeforeChange(this.getValue());var n=this.calcValueByPos(e);this.startValue=n,this.startPosition=e;var r=this.state,o=r.bounds,i=1;if(this.props.range){for(var a=0,s=1;s<o.length-1;++s)n>o[s]&&(a=s);Math.abs(o[a+1]-n)<Math.abs(o[a]-n)&&(a+=1),i=a;var l=o[a+1]===o[a];l&&(i=r.recent),l&&n!==o[a+1]&&(i=n<o[a+1]?a:a+1)}this.setState({handle:i,recent:i});var u=r.bounds[i];if(n!==u){var c=[].concat((0,f["default"])(r.bounds));c[i]=n,this.onChange({bounds:c})}},t.prototype.getValue=function(){var e=this.state.bounds;return this.props.range?e:e[1]},t.prototype.getSliderLength=function(){var e=this.refs.slider;return e?this.props.vertical?e.clientHeight:e.clientWidth:0},t.prototype.getSliderStart=function(){var e=this.refs.slider,t=e.getBoundingClientRect();return this.props.vertical?t.top:t.left},t.prototype.getPrecision=function(e){var t=e.toString(),n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n},t.prototype.getPoints=function(){var e=this.props,t=e.marks,n=e.step,r=e.min,o=e.max,i=this._getPointsCache;if(!i||i.marks!==t||i.step!==n){var a=(0,h["default"])({},t);if(null!==n)for(var s=r;s<=o;s+=n)a[s]=s;var l=Object.keys(a).map(parseFloat);l.sort(function(e,t){return e-t}),this._getPointsCache={marks:t,step:n,points:l}}return this._getPointsCache.points},t.prototype.isValueOutOfBounds=function(e,t){return e<t.min||e>t.max},t.prototype.trimAlignValue=function(e,t){var n=this.state||{},r=n.handle,o=n.bounds,i=(0,h["default"])({},this.props,t||{}),a=i.marks,s=i.step,l=i.min,u=i.max,c=i.allowCross,p=e;p<=l&&(p=l),p>=u&&(p=u),!c&&null!=r&&r>0&&p<=o[r-1]&&(p=o[r-1]),!c&&null!=r&&r<o.length-1&&p>=o[r+1]&&(p=o[r+1]);var f=Object.keys(a).map(parseFloat);if(null!==s){var d=Math.round((p-l)/s)*s+l;f.push(d)}var y=f.map(function(e){return Math.abs(p-e)}),v=f[y.indexOf(Math.min.apply(Math,y))];return null!==s?parseFloat(v.toFixed(this.getPrecision(s))):v},t.prototype.pushHandleOnePoint=function(e,t,n){var r=this.getPoints(),o=r.indexOf(e[t]),i=o+n;if(i>=r.length||i<0)return!1;var a=t+n,s=r[i],l=this.props.pushable,u=n*(e[a]-s);return!!this.pushHandle(e,a,n,l-u)&&(e[t]=s,!0)},t.prototype.pushHandle=function(e,t,n,r){for(var o=e[t],i=e[t];n*(i-o)<r;){if(!this.pushHandleOnePoint(e,t,n))return e[t]=o,!1;i=e[t]}return!0},t.prototype.pushSurroundingHandles=function(e,t,n){var r=this.props.pushable,o=e[t],i=0;if(e[t+1]-o<r?i=1:o-e[t-1]<r&&(i=-1),0!==i){var a=t+i,s=i*(e[a]-o);this.pushHandle(e,a,i,r-s)||(e[t]=n)}},t.prototype.calcOffset=function(e){var t=this.props,n=t.min,r=t.max,o=(e-n)/(r-n);return 100*o},t.prototype.calcValue=function(e){var t=this.props,n=t.vertical,r=t.min,o=t.max,i=Math.abs(e/this.getSliderLength()),a=n?(1-i)*(o-r)+r:i*(o-r)+r;return a},t.prototype.calcValueByPos=function(e){var t=e-this.getSliderStart(),n=this.trimAlignValue(this.calcValue(t));return n},t.prototype.addDocumentEvents=function(e){"touch"===e?(this.onTouchMoveListener=(0,w["default"])(document,"touchmove",this.onTouchMove.bind(this)),this.onTouchUpListener=(0,w["default"])(document,"touchend",this.end.bind(this,"touch"))):"mouse"===e&&(this.onMouseMoveListener=(0,w["default"])(document,"mousemove",this.onMouseMove.bind(this)),this.onMouseUpListener=(0,w["default"])(document,"mouseup",this.end.bind(this,"mouse")))},t.prototype.removeEvents=function(e){"touch"===e?(this.onTouchMoveListener.remove(),this.onTouchUpListener.remove()):"mouse"===e&&(this.onMouseMoveListener.remove(),this.onMouseUpListener.remove())},t.prototype.end=function(e){this.removeEvents(e),this.props.onAfterChange(this.getValue()),this.setState({handle:null})},t.prototype.render=function(){var e,t=this,n=this.state,r=n.handle,i=n.bounds,a=this.props,s=a.className,l=a.prefixCls,u=a.disabled,p=a.vertical,f=a.dots,d=a.included,y=a.range,v=a.step,m=a.marks,g=a.max,b=a.min,P=a.tipTransitionName,O=a.tipFormatter,w=a.children,x=this.props.handle,S=i.map(function(e){return t.calcOffset(e)}),N=l+"-handle",j=i.map(function(e,t){var n;return(0,E["default"])((n={},(0,c["default"])(n,N,!0),(0,c["default"])(n,N+"-"+(t+1),!0),(0,c["default"])(n,N+"-lower",0===t),(0,c["default"])(n,N+"-upper",t===i.length-1),n))}),_=null===v||null===O,D={prefixCls:l,noTip:_,tipTransitionName:P,tipFormatter:O,vertical:p},L=i.map(function(e,t){return(0,C.cloneElement)(x,(0,h["default"])({},D,{className:j[t],value:e,offset:S[t],dragging:r===t,key:t}))});y||L.shift();for(var V=d||y,I=[],F=1;F<i.length;++F){var R,K=(0,E["default"])((R={},(0,c["default"])(R,l+"-track",!0),(0,c["default"])(R,l+"-track-"+F,!0),R));I.push(T["default"].createElement(k["default"],{className:K,vertical:p,included:V,offset:S[F-1],length:S[F]-S[F-1],key:F}))}var W=(0,E["default"])((e={},(0,c["default"])(e,l,!0),(0,c["default"])(e,l+"-disabled",u),(0,c["default"])(e,s,!!s),(0,c["default"])(e,l+"-vertical",this.props.vertical),e));return T["default"].createElement("div",{ref:"slider",className:W,onTouchStart:u?o:this.onTouchStart.bind(this),onMouseDown:u?o:this.onMouseDown.bind(this)},I,T["default"].createElement(M["default"],{prefixCls:l,vertical:p,marks:m,dots:f,step:v,included:V,lowerBound:i[0],upperBound:i[i.length-1],max:g,min:b}),L,T["default"].createElement(A["default"],{className:l+"-mark",vertical:p,marks:m,included:V,lowerBound:i[0],upperBound:i[i.length-1],max:g,min:b}),w)},t}(T["default"].Component);L.propTypes={min:T["default"].PropTypes.number,max:T["default"].PropTypes.number,step:T["default"].PropTypes.number,defaultValue:T["default"].PropTypes.oneOfType([T["default"].PropTypes.number,T["default"].PropTypes.arrayOf(T["default"].PropTypes.number)]),value:T["default"].PropTypes.oneOfType([T["default"].PropTypes.number,T["default"].PropTypes.arrayOf(T["default"].PropTypes.number)]),marks:T["default"].PropTypes.object,included:T["default"].PropTypes.bool,className:T["default"].PropTypes.string,prefixCls:T["default"].PropTypes.string,disabled:T["default"].PropTypes.bool,children:T["default"].PropTypes.any,onBeforeChange:T["default"].PropTypes.func,onChange:T["default"].PropTypes.func,onAfterChange:T["default"].PropTypes.func,handle:T["default"].PropTypes.element,tipTransitionName:T["default"].PropTypes.string,tipFormatter:T["default"].PropTypes.func,dots:T["default"].PropTypes.bool,range:T["default"].PropTypes.oneOfType([T["default"].PropTypes.bool,T["default"].PropTypes.number]),vertical:T["default"].PropTypes.bool,allowCross:T["default"].PropTypes.bool,pushable:T["default"].PropTypes.oneOfType([T["default"].PropTypes.bool,T["default"].PropTypes.number])},L.defaultProps={prefixCls:"rc-slider",className:"",tipTransitionName:"",min:0,max:100,step:1,marks:{},handle:T["default"].createElement(j["default"],null),onBeforeChange:o,onChange:o,onAfterChange:o,tipFormatter:function(e){return e},included:!0,disabled:!1,dots:!1,range:!1,vertical:!1,allowCross:!0,pushable:!1},t["default"]=L,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o,i){(0,f["default"])(!n||r>0,"`Slider[step]` should be a positive number in order to make Slider[dots] work.");var a=Object.keys(t).map(parseFloat);if(n)for(var s=o;s<=i;s+=r)a.indexOf(s)>=0||a.push(s);return a}Object.defineProperty(t,"__esModule",{value:!0});var i=n(12),a=r(i),s=n(1),l=r(s),u=n(2),c=r(u),p=n(22),f=r(p),d=function(e){var t=e.prefixCls,n=e.vertical,r=e.marks,i=e.dots,s=e.step,u=e.included,p=e.lowerBound,f=e.upperBound,d=e.max,h=e.min,y=d-h,v=o(n,r,i,s,h,d).map(function(e){var r,o=Math.abs(e-h)/y*100+"%",i=n?{bottom:o}:{left:o},s=!u&&e===f||u&&e<=f&&e>=p,d=(0,c["default"])((r={},(0,a["default"])(r,t+"-dot",!0),(0,a["default"])(r,t+"-dot-active",s),r));return l["default"].createElement("span",{className:d,style:i,key:e})});return l["default"].createElement("div",{className:t+"-step"},v)};t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=function(e){var t=e.className,n=e.included,r=e.vertical,o=e.offset,a=e.length,s={visibility:n?"visible":"hidden"};return r?(s.bottom=o+"%",s.height=a+"%"):(s.left=o+"%",s.width=a+"%"),i["default"].createElement("div",{className:t,style:s})};t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(455)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e){var t,n,r=e.className,a=e.prefixCls,l=e.style,c=e.tailWidth,f=e.status,d=void 0===f?"wait":f,h=e.iconPrefix,y=e.icon,v=e.wrapperStyle,m=e.adjustMarginRight,g=e.stepLast,b=e.stepNumber,P=e.description,C=e.title,T=i(e,["className","prefixCls","style","tailWidth","status","iconPrefix","icon","wrapperStyle","adjustMarginRight","stepLast","stepNumber","description","title"]),O=(0,p["default"])((t={},o(t,a+"-icon",!0),o(t,h+"icon",!0),o(t,h+"icon-"+y,y),o(t,h+"icon-check",!y&&"finish"===d),o(t,h+"icon-cross",!y&&"error"===d),t)),w=y||"finish"===d||"error"===d?u["default"].createElement("span",{className:O}):u["default"].createElement("span",{className:a+"-icon"},b),x=(0,p["default"])((n={},o(n,a+"-item",!0),o(n,a+"-item-last",g),o(n,a+"-status-"+d,!0),o(n,a+"-custom",y),o(n,r,!!r),n));return u["default"].createElement("div",s({},T,{className:x,style:s({width:c,marginRight:m},l)}),g?"":u["default"].createElement("div",{className:a+"-tail"},u["default"].createElement("i",null)),u["default"].createElement("div",{className:a+"-step"},u["default"].createElement("div",{className:a+"-head",style:{background:v.background||v.backgroundColor}},u["default"].createElement("div",{className:a+"-head-inner"},w)),u["default"].createElement("div",{className:a+"-main"},u["default"].createElement("div",{className:a+"-title",style:{background:v.background||v.backgroundColor}},C),P?u["default"].createElement("div",{className:a+"-description"},P):"")))}var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(1),u=r(l),c=n(2),p=r(c);a.propTypes={className:l.PropTypes.string,prefixCls:l.PropTypes.string,style:l.PropTypes.object,wrapperStyle:l.PropTypes.object,tailWidth:l.PropTypes.oneOfType([l.PropTypes.number,l.PropTypes.string]),status:l.PropTypes.string,iconPrefix:l.PropTypes.string,icon:l.PropTypes.string,adjustMarginRight:l.PropTypes.oneOfType([l.PropTypes.number,l.PropTypes.string]),stepLast:l.PropTypes.bool,stepNumber:l.PropTypes.string,description:l.PropTypes.any,title:l.PropTypes.any},e.exports=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(4),h=r(d),y=n(2),v=r(y),m=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));return r.culcLastStepOffsetWidth=function(){var e=h["default"].findDOMNode(r);e.children.length>0&&(r.culcTimeout=setTimeout(function(){var t=e.lastChild.offsetWidth+1;r.state.lastStepOffsetWidth!==t&&r.setState({lastStepOffsetWidth:t})}))},r.state={lastStepOffsetWidth:0},r}return u(t,e),t.prototype.componentDidMount=function(){this.culcLastStepOffsetWidth()},t.prototype.componentDidUpdate=function(){this.culcLastStepOffsetWidth()},t.prototype.componentWillUnmount=function(){this.culcTimeout&&clearTimeout(this.culcTimeout)},t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.style,s=void 0===o?{}:o,l=n.className,u=n.children,p=n.direction,d=n.labelPlacement,h=n.iconPrefix,y=n.status,m=n.size,g=n.current,b=a(n,["prefixCls","style","className","children","direction","labelPlacement","iconPrefix","status","size","current"]),P=u.length-1,C=this.state.lastStepOffsetWidth>0,T=(0,v["default"])((e={},i(e,r,!0),i(e,r+"-"+m,m),i(e,r+"-"+p,!0),i(e,r+"-label-"+d,"horizontal"===p),i(e,r+"-hidden",!C),i(e,l,l),e));return f["default"].createElement("div",c({className:T,style:s},b),f["default"].Children.map(u,function(e,o){var i="vertical"!==p&&o!==P&&C?100/P+"%":null,a="vertical"===p||o===P?null:-(t.state.lastStepOffsetWidth/P+1),l={stepNumber:(o+1).toString(),stepLast:o===P,tailWidth:i,adjustMarginRight:a,prefixCls:r,iconPrefix:h,wrapperStyle:s};return"error"===y&&o===g-1&&(l.className=n.prefixCls+"-next-error"),e.props.status||(o===g?l.status=y:o<g?l.status="finish":l.status="wait"),f["default"].cloneElement(e,l)},this))},t}(f["default"].Component);t["default"]=m,m.propTypes={prefixCls:p.PropTypes.string,iconPrefix:p.PropTypes.string,direction:p.PropTypes.string,labelPlacement:p.PropTypes.string,children:p.PropTypes.any,status:p.PropTypes.string,size:p.PropTypes.string},m.defaultProps={prefixCls:"rc-steps",iconPrefix:"rc",direction:"horizontal",labelPlacement:"horizontal",current:0,status:"process",size:""},e.exports=t["default"]},function(e,t,n){"use strict";var r=n(460);r.Step=n(459),e.exports=r},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(){}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=n(2),u=s.createClass({displayName:"Switch",propTypes:{className:s.PropTypes.string,prefixCls:s.PropTypes.string,disabled:s.PropTypes.bool,checkedChildren:s.PropTypes.any,unCheckedChildren:s.PropTypes.any,onChange:s.PropTypes.func,onMouseUp:s.PropTypes.func},getDefaultProps:function(){return{prefixCls:"rc-switch",checkedChildren:null,unCheckedChildren:null,className:"",defaultChecked:!1,onChange:i}},getInitialState:function(){var e=this.props,t=!1;return t="checked"in e?!!e.checked:!!e.defaultChecked,{checked:t}},componentWillReceiveProps:function(e){"checked"in e&&this.setState({checked:!!e.checked})},setChecked:function(e){"checked"in this.props||this.setState({checked:e}),this.props.onChange(e)},toggle:function(){var e=!this.state.checked;this.setChecked(e)},handleKeyDown:function(e){37===e.keyCode&&this.setChecked(!1),39===e.keyCode&&this.setChecked(!0)},handleMouseUp:function(e){this.refs.node&&this.refs.node.blur(),this.props.onMouseUp&&this.props.onMouseUp(e)},render:function(){var e,t=this.props,n=t.className,u=t.prefixCls,c=t.disabled,p=t.checkedChildren,f=t.unCheckedChildren,d=r(t,["className","prefixCls","disabled","checkedChildren","unCheckedChildren"]),h=this.state.checked,y=l((e={},o(e,n,!!n),o(e,u,!0),o(e,u+"-checked",h),o(e,u+"-disabled",c),e));return s.createElement("span",a({},d,{className:y,tabIndex:"0",ref:"node",onKeyDown:this.handleKeyDown,onClick:c?i:this.toggle,onMouseUp:this.handleMouseUp}),s.createElement("span",{className:u+"-inner"},h?p:f))}});e.exports=u},function(e,t,n){"use strict";e.exports=n(462)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),s=r(a),l=n(466),u=r(l),c=n(468),p=n(41),f=r(p),d=n(20),h=r(d),y=s["default"].createClass({displayName:"Table",propTypes:{data:a.PropTypes.array,expandIconAsCell:a.PropTypes.bool,defaultExpandAllRows:a.PropTypes.bool,expandedRowKeys:a.PropTypes.array,defaultExpandedRowKeys:a.PropTypes.array,useFixedHeader:a.PropTypes.bool,columns:a.PropTypes.array,prefixCls:a.PropTypes.string,bodyStyle:a.PropTypes.object,style:a.PropTypes.object,rowKey:a.PropTypes.oneOfType([a.PropTypes.string,a.PropTypes.func]),rowClassName:a.PropTypes.func,expandedRowClassName:a.PropTypes.func,childrenColumnName:a.PropTypes.string,onExpand:a.PropTypes.func,onExpandedRowsChange:a.PropTypes.func,indentSize:a.PropTypes.number,onRowClick:a.PropTypes.func,columnsPageRange:a.PropTypes.array,columnsPageSize:a.PropTypes.number,expandIconColumnIndex:a.PropTypes.number,showHeader:a.PropTypes.bool,title:a.PropTypes.func,footer:a.PropTypes.func,emptyText:a.PropTypes.func,scroll:a.PropTypes.object,rowRef:a.PropTypes.func,getBodyWrapper:a.PropTypes.func},getDefaultProps:function(){return{data:[],useFixedHeader:!1,expandIconAsCell:!1,columns:[],defaultExpandAllRows:!1,defaultExpandedRowKeys:[],rowKey:"key",rowClassName:function(){return""},expandedRowClassName:function(){return""},onExpand:function(){},onExpandedRowsChange:function(){},prefixCls:"rc-table",bodyStyle:{},style:{},childrenColumnName:"children",indentSize:15,columnsPageSize:5,expandIconColumnIndex:0,showHeader:!0,scroll:{},rowRef:function(){return null},getBodyWrapper:function(e){return e},emptyText:function(){return"No Data"}}},getInitialState:function(){var e=this.props,t=[],n=[].concat(o(e.data));if(e.defaultExpandAllRows)for(var r=0;r<n.length;r++){var i=n[r];t.push(this.getRowKey(i)),n=n.concat(i[e.childrenColumnName]||[])}else t=e.expandedRowKeys||e.defaultExpandedRowKeys;return{expandedRowKeys:t,data:e.data,currentColumnsPage:0,currentHoverKey:null,scrollPosition:"left",fixedColumnsHeadRowsHeight:[],fixedColumnsBodyRowsHeight:[]}},componentDidMount:function(){this.resetScrollY();var e=this.isAnyColumnsFixed();e&&(this.syncFixedTableRowHeight(),this.resizeEvent=(0,h["default"])(window,"resize",(0,c.debounce)(this.syncFixedTableRowHeight,150)))},componentWillReceiveProps:function(e){"data"in e&&(this.setState({data:e.data}),e.data&&0!==e.data.length||this.resetScrollY()),"expandedRowKeys"in e&&this.setState({expandedRowKeys:e.expandedRowKeys}),e.columns!==this.props.columns&&(delete this.isAnyColumnsFixedCache,delete this.isAnyColumnsLeftFixedCache,delete this.isAnyColumnsRightFixedCache)},componentDidUpdate:function(){this.syncFixedTableRowHeight()},componentWillUnmount:function(){clearTimeout(this.timer),this.resizeEvent&&this.resizeEvent.remove()},onExpandedRowsChange:function(e){this.props.expandedRowKeys||this.setState({expandedRowKeys:e}),this.props.onExpandedRowsChange(e)},onExpanded:function(e,t,n){n&&(n.preventDefault(),n.stopPropagation());var r=this.findExpandedRow(t);if("undefined"==typeof r||e){if(!r&&e){var o=this.getExpandedRows().concat();o.push(this.getRowKey(t)),this.onExpandedRowsChange(o)}}else this.onRowDestroy(t);this.props.onExpand(e,t)},onRowDestroy:function(e){var t=this.getExpandedRows().concat(),n=this.getRowKey(e),r=-1;t.forEach(function(e,t){e===n&&(r=t)}),r!==-1&&t.splice(r,1),this.onExpandedRowsChange(t)},getRowKey:function(e,t){var n=this.props.rowKey;return"function"==typeof n?n(e,t):"undefined"!=typeof e[n]?e[n]:t},getExpandedRows:function(){return this.props.expandedRowKeys||this.state.expandedRowKeys},getHeader:function(e,t){var n=this.props,r=n.showHeader,o=n.expandIconAsCell,i=n.prefixCls,a=[];o&&"right"!==t&&a.push({key:"rc-table-expandIconAsCell",className:i+"-expand-icon-th",title:""}),a=a.concat(e||this.getCurrentColumns()).map(function(e){if(0!==e.colSpan)return s["default"].createElement("th",{key:e.key,colSpan:e.colSpan,className:e.className||""},e.title)});var l=this.state.fixedColumnsHeadRowsHeight,u=l[0]&&e?{height:l[0]}:null;return r?s["default"].createElement("thead",{className:i+"-thead"},s["default"].createElement("tr",{style:u},a)):null},getExpandedRow:function(e,t,n,r,o){var i=this.props.prefixCls;return s["default"].createElement("tr",{key:e+"-extra-row",style:{display:n?"":"none"},className:i+"-expanded-row "+r},this.props.expandIconAsCell&&"right"!==o?s["default"].createElement("td",{key:"rc-table-expand-icon-placeholder"}):null,s["default"].createElement("td",{colSpan:this.props.columns.length},"right"!==o?t:"&nbsp;"))},getRowsByData:function(e,t,n,r,o){for(var a=this.props,l=a.childrenColumnName,c=a.expandedRowRender,p=a.expandRowByClick,f=this.state.fixedColumnsBodyRowsHeight,d=[],h=a.rowClassName,y=a.rowRef,v=a.expandedRowClassName,m=a.data.some(function(e){return e[l]}),g=a.onRowClick,b=this.isAnyColumnsFixed(),P="right"!==o&&a.expandIconAsCell,C="right"!==o?a.expandIconColumnIndex:-1,T=0;T<e.length;T++){var O=e[T],w=this.getRowKey(O,T),x=O[l],E=this.isRowExpanded(O),S=void 0;c&&E&&(S=c(O,T,n));var k=h(O,T,n);this.state.currentHoverKey===w&&(k+=" "+a.prefixCls+"-row-hover");var N={};b&&(N.onHover=this.handleRowHover);var j=o&&f[T]?{height:f[T]}:{};d.push(s["default"].createElement(u["default"],i({indent:n,indentSize:a.indentSize,needIndentSpaced:m,className:k,record:O,expandIconAsCell:P,onDestroy:this.onRowDestroy,index:T,visible:t,expandRowByClick:p,onExpand:this.onExpanded,expandable:x||c,expanded:E,prefixCls:a.prefixCls+"-row",childrenColumnName:l,columns:r||this.getCurrentColumns(),expandIconColumnIndex:C,onRowClick:g,style:j},N,{key:w,hoverKey:w,ref:y(O,T,n)})));var _=t&&E;S&&E&&d.push(this.getExpandedRow(w,S,_,v(O,T,n),o)),x&&(d=d.concat(this.getRowsByData(x,_,n+1,r,o)))}return d},getRows:function(e,t){return this.getRowsByData(this.state.data,!0,0,e,t)},getColGroup:function(e,t){var n=[];return this.props.expandIconAsCell&&"right"!==t&&n.push(s["default"].createElement("col",{className:this.props.prefixCls+"-expand-icon-col",key:"rc-table-expand-icon-col"})),n=n.concat((e||this.props.columns).map(function(e){return s["default"].createElement("col",{key:e.key,style:{width:e.width,minWidth:e.width}})})),s["default"].createElement("colgroup",null,n)},getCurrentColumns:function(){var e=this,t=this.props,n=t.columns,r=t.columnsPageRange,o=t.columnsPageSize,a=t.prefixCls,s=this.state.currentColumnsPage;return!r||r[0]>r[1]?n:n.map(function(t,n){var l=i({},t);if(n>=r[0]&&n<=r[1]){var u=r[0]+s*o,c=r[0]+(s+1)*o-1;c>r[1]&&(c=r[1]),(n<u||n>c)&&(l.className=l.className||"",l.className+=" "+a+"-column-hidden"),l=e.wrapPageColumn(l,n===u,n===c)}return l})},getLeftFixedTable:function(){var e=this.props.columns,t=e.filter(function(e){return"left"===e.fixed||e.fixed===!0});return this.getTable({columns:t,fixed:"left"})},getRightFixedTable:function(){var e=this.props.columns,t=e.filter(function(e){return"right"===e.fixed});return this.getTable({columns:t,fixed:"right"})},getTable:function(){var e=this,t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=t.columns,r=t.fixed,o=this.props,a=o.prefixCls,l=o.scroll,u=void 0===l?{}:l,p=o.getBodyWrapper,f=this.props.useFixedHeader,d=i({},this.props.bodyStyle),h={},y="";if((u.x||n)&&(y=a+"-fixed",d.overflowX=d.overflowX||"auto"),u.y){r?d.height=d.height||u.y:d.maxHeight=d.maxHeight||u.y,d.overflowY=d.overflowY||"scroll",f=!0;var v=(0,c.measureScrollbar)();v>0&&((r?d:h).marginBottom="-"+v+"px",(r?d:h).paddingBottom="0px")}var m=function(){var t=arguments.length<=0||void 0===arguments[0]||arguments[0],o=arguments.length<=1||void 0===arguments[1]||arguments[1],i={};!n&&u.x&&(u.x===!0?i.tableLayout="fixed":i.width=u.x);var l=o?p(s["default"].createElement("tbody",{className:a+"-tbody"},e.getRows(n,r))):null;return s["default"].createElement("table",{className:y,style:i},e.getColGroup(n,r),t?e.getHeader(n,r):null,l)},g=void 0;f&&(g=s["default"].createElement("div",{className:a+"-header",ref:n?null:"headTable",style:h,onMouseOver:this.detectScrollTarget,onTouchStart:this.detectScrollTarget,onScroll:this.handleBodyScroll},m(!0,!1)));var b=s["default"].createElement("div",{className:a+"-body",style:d,ref:"bodyTable",onMouseOver:this.detectScrollTarget,onTouchStart:this.detectScrollTarget,onScroll:this.handleBodyScroll},m(!f));if(n&&n.length){var P=void 0;"left"===n[0].fixed||n[0].fixed===!0?P="fixedColumnsBodyLeft":"right"===n[0].fixed&&(P="fixedColumnsBodyRight"),delete d.overflowX,delete d.overflowY,b=s["default"].createElement("div",{className:a+"-body-outer",style:i({},d)},s["default"].createElement("div",{className:a+"-body-inner",ref:P,onMouseOver:this.detectScrollTarget,onTouchStart:this.detectScrollTarget,onScroll:this.handleBodyScroll},m(!f)))}return s["default"].createElement("span",null,g,b)},getTitle:function(){var e=this.props,t=e.title,n=e.prefixCls;return t?s["default"].createElement("div",{className:n+"-title"},t(this.state.data)):null},getFooter:function(){var e=this.props,t=e.footer,n=e.prefixCls;return t?s["default"].createElement("div",{className:n+"-footer"},t(this.state.data)):null},getEmptyText:function(){var e=this.props,t=e.emptyText,n=e.prefixCls,r=e.data;return r.length?null:s["default"].createElement("div",{className:n+"-placeholder"},t())},getMaxColumnsPage:function(){var e=this.props,t=e.columnsPageRange,n=e.columnsPageSize;return Math.ceil((t[1]-t[0]+1)/n)-1},goToColumnsPage:function(e){var t=this.getMaxColumnsPage(),n=e;n<0&&(n=0),n>t&&(n=t),this.setState({currentColumnsPage:n})},syncFixedTableRowHeight:function(){var e=this,t=this.props.prefixCls,n=this.refs.headTable?this.refs.headTable.querySelectorAll("tr"):[],r=this.refs.bodyTable.querySelectorAll("."+t+"-row")||[],o=[].map.call(n,function(e){ return e.getBoundingClientRect().height||"auto"}),i=[].map.call(r,function(e){return e.getBoundingClientRect().height||"auto"});(0,f["default"])(this.state.fixedColumnsHeadRowsHeight,o)&&(0,f["default"])(this.state.fixedColumnsBodyRowsHeight,i)||(this.timer=setTimeout(function(){e.setState({fixedColumnsHeadRowsHeight:o,fixedColumnsBodyRowsHeight:i})}))},resetScrollY:function(){this.refs.headTable&&(this.refs.headTable.scrollLeft=0),this.refs.bodyTable&&(this.refs.bodyTable.scrollLeft=0)},prevColumnsPage:function(){this.goToColumnsPage(this.state.currentColumnsPage-1)},nextColumnsPage:function(){this.goToColumnsPage(this.state.currentColumnsPage+1)},wrapPageColumn:function(e,t,n){var r=this.props.prefixCls,o=this.state.currentColumnsPage,i=this.getMaxColumnsPage(),a=r+"-prev-columns-page";0===o&&(a+=" "+r+"-prev-columns-page-disabled");var l=s["default"].createElement("span",{className:a,onClick:this.prevColumnsPage}),u=r+"-next-columns-page";o===i&&(u+=" "+r+"-next-columns-page-disabled");var c=s["default"].createElement("span",{className:u,onClick:this.nextColumnsPage});return t&&(e.title=s["default"].createElement("span",null,l,e.title),e.className=(e.className||"")+" "+r+"-column-has-prev"),n&&(e.title=s["default"].createElement("span",null,e.title,c),e.className=(e.className||"")+" "+r+"-column-has-next"),e},findExpandedRow:function(e){var t=this,n=this.getExpandedRows().filter(function(n){return n===t.getRowKey(e)});return n[0]},isRowExpanded:function(e){return"undefined"!=typeof this.findExpandedRow(e)},detectScrollTarget:function(e){this.scrollTarget!==e.currentTarget&&(this.scrollTarget=e.currentTarget)},isAnyColumnsFixed:function(){return"isAnyColumnsFixedCache"in this?this.isAnyColumnsFixedCache:(this.isAnyColumnsFixedCache=this.getCurrentColumns().some(function(e){return!!e.fixed}),this.isAnyColumnsFixedCache)},isAnyColumnsLeftFixed:function(){return"isAnyColumnsLeftFixedCache"in this?this.isAnyColumnsLeftFixedCache:(this.isAnyColumnsLeftFixedCache=this.getCurrentColumns().some(function(e){return"left"===e.fixed||e.fixed===!0}),this.isAnyColumnsLeftFixedCache)},isAnyColumnsRightFixed:function(){return"isAnyColumnsRightFixedCache"in this?this.isAnyColumnsRightFixedCache:(this.isAnyColumnsRightFixedCache=this.getCurrentColumns().some(function(e){return"right"===e.fixed}),this.isAnyColumnsRightFixedCache)},handleBodyScroll:function(e){if(e.target===this.scrollTarget){var t=this.props.scroll,n=void 0===t?{}:t,r=this.refs,o=r.headTable,i=r.bodyTable,a=r.fixedColumnsBodyLeft,s=r.fixedColumnsBodyRight;n.x&&(e.target===i&&o?o.scrollLeft=e.target.scrollLeft:e.target===o&&i&&(i.scrollLeft=e.target.scrollLeft),0===e.target.scrollLeft?this.setState({scrollPosition:"left"}):e.target.scrollLeft+1>=e.target.children[0].getBoundingClientRect().width-e.target.getBoundingClientRect().width?this.setState({scrollPosition:"right"}):"middle"!==this.state.scrollPosition&&this.setState({scrollPosition:"middle"})),n.y&&(a&&e.target!==a&&(a.scrollTop=e.target.scrollTop),s&&e.target!==s&&(s.scrollTop=e.target.scrollTop),i&&e.target!==i&&(i.scrollTop=e.target.scrollTop))}},handleRowHover:function(e,t){this.setState({currentHoverKey:e?t:null})},render:function(){var e=this.props,t=e.prefixCls,n=e.prefixCls;e.className&&(n+=" "+e.className),e.columnsPageRange&&(n+=" "+t+"-columns-paging"),(e.useFixedHeader||e.scroll&&e.scroll.y)&&(n+=" "+t+"-fixed-header"),n+=" "+t+"-scroll-position-"+this.state.scrollPosition;var r=this.isAnyColumnsFixed()||e.scroll.x||e.scroll.y;return s["default"].createElement("div",{className:n,style:e.style},this.getTitle(),s["default"].createElement("div",{className:t+"-content"},this.isAnyColumnsLeftFixed()&&s["default"].createElement("div",{className:t+"-fixed-left"},this.getLeftFixedTable()),s["default"].createElement("div",{className:r?t+"-scroll":""},this.getTable(),this.getEmptyText(),this.getFooter()),this.isAnyColumnsRightFixed()&&s["default"].createElement("div",{className:t+"-fixed-right"},this.getRightFixedTable())))}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(382),s=r(a),l=n(41),u=r(l),c=n(157),p=r(c),f=i["default"].createClass({displayName:"TableCell",propTypes:{record:o.PropTypes.object,prefixCls:o.PropTypes.string,isColumnHaveExpandIcon:o.PropTypes.bool,index:o.PropTypes.number,expanded:o.PropTypes.bool,expandable:o.PropTypes.any,onExpand:o.PropTypes.func,needIndentSpaced:o.PropTypes.bool,indent:o.PropTypes.number,indentSize:o.PropTypes.number,column:o.PropTypes.object},shouldComponentUpdate:function(e){return!(0,u["default"])(e,this.props)},isInvalidRenderCellText:function(e){return e&&!i["default"].isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)},render:function d(){var e=this.props,t=e.record,n=e.indentSize,r=e.prefixCls,o=e.indent,a=e.isColumnHaveExpandIcon,l=e.index,u=e.expandable,c=e.onExpand,f=e.needIndentSpaced,h=e.expanded,y=e.column,v=y.dataIndex,d=y.render,m=y.className,g=s["default"].get(t,v),b=void 0,P=void 0,C=void 0;d&&(g=d(g,t,l),this.isInvalidRenderCellText(g)&&(b=g.props||{},C=b.rowSpan,P=b.colSpan,g=g.children)),this.isInvalidRenderCellText(g)&&(g=null);var T=i["default"].createElement(p["default"],{expandable:u,prefixCls:r,onExpand:c,needIndentSpaced:f,expanded:h,record:t}),O=i["default"].createElement("span",{style:{paddingLeft:n*o+"px"},className:r+"-indent indent-level-"+o});return 0===C||0===P?null:i["default"].createElement("td",{colSpan:P,rowSpan:C,className:m||""},a?O:null,a?T:null,g)}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(41),l=r(s),u=n(465),c=r(u),p=n(157),f=r(p),d=a["default"].createClass({displayName:"TableRow",propTypes:{onDestroy:i.PropTypes.func,onRowClick:i.PropTypes.func,record:i.PropTypes.object,prefixCls:i.PropTypes.string,expandIconColumnIndex:i.PropTypes.number,onHover:i.PropTypes.func,columns:i.PropTypes.array,style:i.PropTypes.object,visible:i.PropTypes.bool,index:i.PropTypes.number,hoverKey:i.PropTypes.any,expanded:i.PropTypes.bool,expandable:i.PropTypes.any,onExpand:i.PropTypes.func,needIndentSpaced:i.PropTypes.bool,className:i.PropTypes.string,indent:i.PropTypes.number,indentSize:i.PropTypes.number,expandIconAsCell:i.PropTypes.bool,expandRowByClick:i.PropTypes.bool},getDefaultProps:function(){return{onRowClick:function(){},onDestroy:function(){},expandIconColumnIndex:0,expandRowByClick:!1,onHover:function(){}}},shouldComponentUpdate:function(e){return!(0,l["default"])(e,this.props)},componentWillUnmount:function(){this.props.onDestroy(this.props.record)},onRowClick:function h(e){var t=this.props,n=t.record,r=t.index,h=t.onRowClick,o=t.expandable,i=t.expandRowByClick,a=t.expanded,s=t.onExpand;o&&i&&s(!a,n),h(n,r,e)},onMouseEnter:function(){var e=this.props,t=e.onHover,n=e.hoverKey;t(!0,n)},onMouseLeave:function(){var e=this.props,t=e.onHover,n=e.hoverKey;t(!1,n)},render:function(){for(var e=this.props,t=e.prefixCls,n=e.columns,r=e.record,i=e.style,s=e.visible,l=e.index,u=e.expandIconColumnIndex,p=e.expandIconAsCell,d=e.expanded,h=e.expandRowByClick,y=e.expandable,v=e.onExpand,m=e.needIndentSpaced,g=e.className,b=e.indent,P=e.indentSize,C=[],T=0;T<n.length;T++){p&&0===T&&C.push(a["default"].createElement("td",{className:t+"-expand-icon-cell",key:"rc-table-expand-icon-cell"},a["default"].createElement(f["default"],{expandable:y,prefixCls:t,onExpand:v,needIndentSpaced:m,expanded:d,record:r})));var O=!p&&!h&&T===u;C.push(a["default"].createElement(c["default"],{prefixCls:t,record:r,indentSize:P,indent:b,index:l,expandable:y,onExpand:v,needIndentSpaced:m,expanded:d,isColumnHaveExpandIcon:O,column:n[T],key:n[T].key}))}return a["default"].createElement("tr",{onClick:this.onRowClick,onMouseEnter:this.onMouseEnter,onMouseLeave:this.onMouseLeave,className:t+" "+g+" "+t+"-level-"+b,style:s?i:o({},i,{display:"none"})},C)}});t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(464)},function(e,t){"use strict";function n(){if("undefined"==typeof document||"undefined"==typeof window)return 0;if(o)return o;var e=document.createElement("div");for(var t in i)i.hasOwnProperty(t)&&(e.style[t]=i[t]);document.body.appendChild(e);var n=e.offsetWidth-e.clientWidth;return document.body.removeChild(e),o=n}function r(e,t,n){var r=void 0;return function(){var o=this,i=arguments;i[0]&&i[0].persist&&i[0].persist();var a=function(){r=null,n||e.apply(o,i)},s=n&&!r;clearTimeout(r),r=setTimeout(a,t),s&&e.apply(o,i)}}Object.defineProperty(t,"__esModule",{value:!0}),t.measureScrollbar=n,t.debounce=r;var o=void 0,i={position:"absolute",top:"-9999px",width:"50px",height:"50px",overflow:"scroll"}},function(e,t,n){"use strict";function r(e){var t=e.refs,n=t.nav,r=(0,o.offset)(n),i=t.inkBar,a=t.activeTab,s=e.props.tabPosition;if(a){var l=a,u=(0,o.offset)(l),c=(0,o.getTransformPropertyName)();if("top"===s||"bottom"===s){var p=u.left-r.left;c?(i.style[c]="translate3d("+p+"px,0,0)",i.style.width=l.offsetWidth+"px",i.style.height=""):(i.style.left=p+"px",i.style.top="",i.style.bottom="",i.style.right=n.offsetWidth-p-l.offsetWidth+"px")}else{var f=u.top-r.top;c?(i.style[c]="translate3d(0,"+f+"px,0)",i.style.height=l.offsetHeight+"px",i.style.width=""):(i.style.left="",i.style.right="",i.style.top=f+"px",i.style.bottom=n.offsetHeight-f-l.offsetHeight+"px")}}i.style.display=a?"block":"none"}Object.defineProperty(t,"__esModule",{value:!0});var o=n(159);t["default"]={componentDidUpdate:function(){r(this)},componentDidMount:function(){r(this)}},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={LEFT:37,UP:38,RIGHT:39,DOWN:40},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var i=n(12),a=r(i),s=n(7),l=r(s),u=n(1),c=r(u),p=n(2),f=r(p),d=n(469),h=r(d),y=n(159),v={"float":"right"},m=c["default"].createClass({displayName:"Nav",propTypes:{tabPosition:u.PropTypes.string,tabBarExtraContent:u.PropTypes.any,onTabClick:u.PropTypes.func,onKeyDown:u.PropTypes.func},mixins:[h["default"]],getInitialState:function(){return this.offset=0,{next:!1,prev:!1}},componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(e){var t=this.props;if(e&&e.tabPosition!==t.tabPosition)return void this.setOffset(0);var n=this.setNextPrev();this.isNextPrevShown(this.state)!==this.isNextPrevShown(n)?this.setState({},this.scrollToActiveTab):e&&t.activeKey===e.activeKey||this.scrollToActiveTab()},onTabClick:function(e){this.props.onTabClick(e)},setNextPrev:function(){var e=this.refs.nav,t=this.getOffsetWH(e),n=this.refs.navWrap,r=this.getOffsetWH(n),o=this.offset,i=r-t,a=this.state,s=a.next,l=a.prev;return i>=0?(s=!1,this.setOffset(0,!1),o=0):i<o?s=!0:(s=!1,this.setOffset(i,!1),o=i),l=o<0,this.setNext(s),this.setPrev(l),{next:s,prev:l}},getTabs:function(){var e=this,t=this.props,n=t.panels,r=t.activeKey,o=[],i=t.prefixCls;return c["default"].Children.forEach(n,function(t){var n=t.key,a=r===n?i+"-tab-active":"";a+=" "+i+"-tab";var s={};t.props.disabled?a+=" "+i+"-tab-disabled":s={onClick:e.onTabClick.bind(e,n)};var u={};r===n&&(u.ref="activeTab"),o.push(c["default"].createElement("div",(0,l["default"])({role:"tab","aria-disabled":t.props.disabled?"true":"false","aria-selected":r===n?"true":"false"},s,{className:a,key:n},u),c["default"].createElement("div",{className:i+"-tab-inner"},t.props.tab)))}),o},getOffsetWH:function(e){var t=this.props.tabPosition,n="offsetWidth";return"left"!==t&&"right"!==t||(n="offsetHeight"),e[n]},getOffsetLT:function(e){var t=this.props.tabPosition,n="left";return"left"!==t&&"right"!==t||(n="top"),e.getBoundingClientRect()[n]},setOffset:function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1],n=Math.min(0,e);if(this.offset!==n){this.offset=n;var r={},o=this.props.tabPosition,i=(0,y.getTransformPropertyName)();r="left"===o||"right"===o?i?{name:i,value:"translate3d(0,"+n+"px,0)"}:{name:"top",value:n+"px"}:i?{name:i,value:"translate3d("+n+"px,0,0)"}:{name:"left",value:n+"px"},this.refs.nav.style[r.name]=r.value,t&&this.setNextPrev()}},setPrev:function(e){this.state.prev!==e&&this.setState({prev:e})},setNext:function(e){this.state.next!==e&&this.setState({next:e})},isNextPrevShown:function(e){return e.next||e.prev},scrollToActiveTab:function(){var e=this.refs,t=e.activeTab,n=e.navWrap;if(t){var r=this.getOffsetWH(t),o=this.getOffsetWH(n),i=this.offset,a=this.getOffsetLT(n),s=this.getOffsetLT(t);a>s?(i+=a-s,this.setOffset(i)):a+o<s+r&&(i-=s+r-(a+o),this.setOffset(i))}},prev:function(){var e=this.refs.navWrap,t=this.getOffsetWH(e),n=this.offset;this.setOffset(n+t)},next:function(){var e=this.refs.navWrap,t=this.getOffsetWH(e),n=this.offset;this.setOffset(n-t)},render:function(){var e=this.props,t=this.state,n=e.prefixCls,r=this.getTabs(),i=e.tabMovingDirection,s=n+"-ink-bar";i&&(s+=" "+n+"-ink-bar-transition-"+i);var l=void 0,u=void 0,p=t.prev||t.next;if(p){var d,h;u=c["default"].createElement("span",{onClick:t.prev?this.prev:o,unselectable:"unselectable",className:(0,f["default"])((d={},(0,a["default"])(d,n+"-tab-prev",1),(0,a["default"])(d,n+"-tab-btn-disabled",!t.prev),d))},c["default"].createElement("span",{className:n+"-tab-prev-icon"})),l=c["default"].createElement("span",{onClick:t.next?this.next:o,unselectable:"unselectable",className:(0,f["default"])((h={},(0,a["default"])(h,n+"-tab-next",1),(0,a["default"])(h,n+"-tab-btn-disabled",!t.next),h))},c["default"].createElement("span",{className:n+"-tab-next-icon"}))}var y=this.props.tabBarExtraContent;return c["default"].createElement("div",{role:"tablist",className:n+"-bar",tabIndex:"0",onKeyDown:this.props.onKeyDown},y?c["default"].createElement("div",{style:v},y):null,c["default"].createElement("div",{className:n+"-nav-container "+(p?n+"-nav-container-scrolling":""),style:e.style,ref:"container"},u,l,c["default"].createElement("div",{className:n+"-nav-wrap",ref:"navWrap"},c["default"].createElement("div",{className:n+"-nav-scroll"},c["default"].createElement("div",{className:n+"-nav",ref:"nav"},c["default"].createElement("div",{className:s,ref:"inkBar"}),r)))))}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e){var t=void 0;return u["default"].Children.forEach(e.children,function(e){t||e.props.disabled||(t=e.key)}),t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(12),s=r(a),l=n(1),u=r(l),c=n(470),p=r(c),f=n(158),d=r(f),h=n(471),y=r(h),v=n(9),m=r(v),g=n(2),b=r(g),P=u["default"].createClass({displayName:"Tabs",propTypes:{destroyInactiveTabPane:l.PropTypes.bool,onTabClick:l.PropTypes.func,onChange:l.PropTypes.func,children:l.PropTypes.any,tabBarExtraContent:l.PropTypes.any,animation:l.PropTypes.string,prefixCls:l.PropTypes.string,className:l.PropTypes.string,tabPosition:l.PropTypes.string},getDefaultProps:function(){return{prefixCls:"rc-tabs",destroyInactiveTabPane:!1,tabBarExtraContent:null,onChange:o,tabPosition:"top",style:{},contentStyle:{},navStyle:{},onTabClick:o}},getInitialState:function(){var e=this.props,t=void 0;return t="activeKey"in e?e.activeKey:"defaultActiveKey"in e?e.defaultActiveKey:i(e),{activeKey:t}},componentWillReceiveProps:function(e){var t=this.state.activeKey;if("activeKey"in e&&(t=e.activeKey,!t))return void this.setState({activeKey:t});var n=void 0;u["default"].Children.forEach(e.children,function(e){e.key===t&&(n=!0)}),n?this.setActiveKey(t,e):this.setActiveKey(i(e),e)},onTabClick:function(e){this.setActiveKey(e),this.props.onTabClick(e),this.state.activeKey!==e&&this.props.onChange(e)},onNavKeyDown:function(e){var t=e.keyCode;if(t===p["default"].RIGHT||t===p["default"].DOWN){e.preventDefault();var n=this.getNextActiveKey(!0);this.onTabClick(n)}else if(t===p["default"].LEFT||t===p["default"].UP){e.preventDefault();var r=this.getNextActiveKey(!1);this.onTabClick(r)}},getNextActiveKey:function(e){var t=this.state.activeKey,n=[];u["default"].Children.forEach(this.props.children,function(t){t.props.disabled||(e?n.push(t):n.unshift(t))});var r=n.length,o=r&&n[0].key;return n.forEach(function(e,i){e.key===t&&(o=i===r-1?n[0].key:n[i+1].key)}),o},getTabPanes:function(){var e=this.state,t=this.props,n=e.activeKey,r=t.children,o=[];return u["default"].Children.forEach(r,function(e){var r=e.key,i=n===r;o.push(u["default"].cloneElement(e,{active:i,rootPrefixCls:t.prefixCls}))}),o},getIndexPair:function(e,t,n){var r=[];u["default"].Children.forEach(e.children,function(e){r.push(e.key)});var o=r.indexOf(t),i=r.indexOf(n);return{currentIndex:o,nextIndex:i}},setActiveKey:function(e,t){var n=t||this.props,r=this.state.activeKey;if(!(r===e||"activeKey"in n&&n===this.props))if(r){var o=this.getIndexPair(n,r,e),i=o.currentIndex,a=o.nextIndex;if(i===-1){var s=this.getIndexPair(this.props,r,e);i=s.currentIndex,a=s.nextIndex}var l=i>a?"backward":"forward";this.setState({activeKey:e,tabMovingDirection:l})}else this.setState({activeKey:e})},render:function(){var e,t=this.props,n=t.destroyInactiveTabPane,r=t.prefixCls,o=t.tabPosition,i=t.className,a=t.animation,l=(0,b["default"])((e={},(0,s["default"])(e,r,1),(0,s["default"])(e,r+"-"+o,1),(0,s["default"])(e,i,!!i),e)),c=this.state.tabMovingDirection,p=this.getTabPanes(),f=void 0;f=t.transitionName&&t.transitionName[c||"backward"],!f&&a&&(f=r+"-"+a+"-"+(c||"backward")),n&&(p=p.filter(function(e){return e.props.active})),f&&(p=n?u["default"].createElement(m["default"],{exclusive:!0,component:"div",transitionName:f},p):u["default"].createElement(m["default"],{showProp:"active",exclusive:!0,component:"div",transitionName:f},p));var d=[u["default"].createElement(y["default"],{prefixCls:r,key:"nav",onKeyDown:this.onNavKeyDown,tabBarExtraContent:this.props.tabBarExtraContent,tabPosition:o,style:t.navStyle,onTabClick:this.onTabClick,tabMovingDirection:c,panels:this.props.children,activeKey:this.state.activeKey}),u["default"].createElement("div",{className:r+"-content",style:t.contentStyle,key:"content"},p)];return"bottom"===o&&d.reverse(),u["default"].createElement("div",{className:l,style:t.style},d)}});P.TabPane=d["default"],t["default"]=P,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.TabPane=t["default"]=void 0;var o=n(472),i=r(o),a=n(158),s=r(a);t["default"]=i["default"],t.TabPane=s["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(160),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(79),i=r(o),a=n(133),s=r(a);t["default"]={clear:"Clear",format:i["default"],calendar:s["default"]},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(131),i=r(o),a=n(134),s=r(a);t["default"]={clear:"\u6e05\u9664",format:i["default"],calendar:s["default"]},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(480),s=r(a),l=n(14),u=r(l),c=function(e,t){var n=""+e;e<10&&(n="0"+e);var r=!1;return t&&t.indexOf(e)>=0&&(r=!0),{value:n,disabled:r}},p=i["default"].createClass({displayName:"Combobox",propTypes:{formatter:o.PropTypes.object,prefixCls:o.PropTypes.string,value:o.PropTypes.object,onChange:o.PropTypes.func,showHour:o.PropTypes.bool,gregorianCalendarLocale:o.PropTypes.object,showSecond:o.PropTypes.bool,hourOptions:o.PropTypes.array,minuteOptions:o.PropTypes.array,secondOptions:o.PropTypes.array,disabledHours:o.PropTypes.func,disabledMinutes:o.PropTypes.func,disabledSeconds:o.PropTypes.func,onCurrentSelectPanelChange:o.PropTypes.func},onItemChange:function(e,t){var n=this.props.onChange,r=this.props.value;r=r?r.clone():this.getNow().clone(),"hour"===e?r.setHourOfDay(t):"minute"===e?r.setMinutes(t):r.setSeconds(t),n(r)},onEnterSelectPanel:function(e){this.props.onCurrentSelectPanelChange(e)},getHourSelect:function(e){var t=this.props,n=t.prefixCls,r=t.hourOptions,o=t.disabledHours,a=t.showHour;if(!a)return null;var l=o();return i["default"].createElement(s["default"],{prefixCls:n,options:r.map(function(e){return c(e,l)}),selectedIndex:r.indexOf(e),type:"hour",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"hour")})},getMinuteSelect:function(e){var t=this.props,n=t.prefixCls,r=t.minuteOptions,o=t.disabledMinutes,a=this.props.value||this.getNow(),l=o(a.getHourOfDay());return i["default"].createElement(s["default"],{prefixCls:n,options:r.map(function(e){return c(e,l)}),selectedIndex:r.indexOf(e),type:"minute",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"minute")})},getSecondSelect:function(e){var t=this.props,n=t.prefixCls,r=t.secondOptions,o=t.disabledSeconds,a=t.showSecond;if(!a)return null;var l=this.props.value||this.getNow(),u=o(l.getHourOfDay(),l.getMinutes());return i["default"].createElement(s["default"],{prefixCls:n,options:r.map(function(e){return c(e,u)}),selectedIndex:r.indexOf(e),type:"second",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"second")})},getNow:function(){if(this.showNow)return this.showNow;var e=new u["default"](this.props.gregorianCalendarLocale);return e.setTime(Date.now()),this.showNow=e,e},render:function(){var e=this.props.prefixCls,t=this.props.value||this.getNow();return i["default"].createElement("div",{className:e+"-combobox"},this.getHourSelect(t.getHourOfDay()),this.getMinuteSelect(t.getMinutes()),this.getSecondSelect(t.getSeconds()))}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(483),s=r(a),l=i["default"].createClass({displayName:"Header",propTypes:{formatter:o.PropTypes.object,prefixCls:o.PropTypes.string,gregorianCalendarLocale:o.PropTypes.object,locale:o.PropTypes.object,disabledDate:o.PropTypes.func,placeholder:o.PropTypes.string,value:o.PropTypes.object,hourOptions:o.PropTypes.array,minuteOptions:o.PropTypes.array,secondOptions:o.PropTypes.array,disabledHours:o.PropTypes.func,disabledMinutes:o.PropTypes.func,disabledSeconds:o.PropTypes.func,onChange:o.PropTypes.func,onClear:o.PropTypes.func,onEsc:o.PropTypes.func,allowEmpty:o.PropTypes.bool,currentSelectPanel:o.PropTypes.string},getInitialState:function(){var e=this.props.value;return{str:e&&this.props.formatter.format(e)||"",invalid:!1}},componentDidMount:function(){this.timer=setTimeout(this.selectRange,0)},componentWillReceiveProps:function(e){var t=e.value;this.setState({str:t&&e.formatter.format(t)||"",invalid:!1})},componentDidUpdate:function(){this.timer=setTimeout(this.selectRange,0)},componentWillUnmount:function(){clearTimeout(this.timer)},onInputChange:function(e){var t=e.target.value;this.setState({str:t});var n=null,r=this.props,o=r.formatter,i=r.gregorianCalendarLocale,a=r.hourOptions,s=r.minuteOptions,l=r.secondOptions,u=r.disabledHours,c=r.disabledMinutes,p=r.disabledSeconds,f=r.onChange,d=r.allowEmpty;if(t){var h=this.props.value;try{n=o.parse(t,{locale:i,obeyCount:!0})}catch(y){return void this.setState({invalid:!0})}if(!n)return void this.setState({invalid:!0});if(a.indexOf(n.getHourOfDay())<0||s.indexOf(n.getMinutes())<0||l.indexOf(n.getSeconds())<0)return void this.setState({invalid:!0});var v=u(),m=c(n.getHourOfDay()),g=p(n.getHourOfDay(),n.getMinutes());if(v&&v.indexOf(n.getHourOfDay())>=0||m&&m.indexOf(n.getMinutes())>=0||g&&g.indexOf(n.getSeconds())>=0)return void this.setState({invalid:!0});if(h&&n){if(h.getHourOfDay()!==n.getHourOfDay()||h.getMinutes()!==n.getMinutes()||h.getSeconds()!==n.getSeconds()){var b=h.clone();b.setHourOfDay(n.getHourOfDay()),b.setMinutes(n.getMinutes()),b.setSeconds(n.getSeconds()),f(b)}}else h!==n&&f(n)}else{if(!d)return void this.setState({invalid:!0});f(null)}this.setState({invalid:!1})},onKeyDown:function(e){27===e.keyCode&&this.props.onEsc()},onClear:function(){this.setState({str:""}),this.props.onClear()},getClearButton:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.allowEmpty;return r?i["default"].createElement("a",{className:n+"-clear-btn",role:"button",title:t.clear,onMouseDown:this.onClear}):null},getInput:function(){var e=this.props,t=e.prefixCls,n=e.placeholder,r=this.state,o=r.invalid,a=r.str,s=o?t+"-input-invalid":"";return i["default"].createElement("input",{className:t+"-input "+s,ref:"input",onKeyDown:this.onKeyDown,value:a,placeholder:n,onChange:this.onInputChange})},selectRange:function(){if(this.refs.input.select(),this.props.currentSelectPanel&&this.refs.input.value){var e=0,t=0;"hour"===this.props.currentSelectPanel?(e=0,t=this.refs.input.value.indexOf(":")):"minute"===this.props.currentSelectPanel?(e=this.refs.input.value.indexOf(":")+1,t=this.refs.input.value.lastIndexOf(":")):"second"===this.props.currentSelectPanel&&(e=this.refs.input.value.lastIndexOf(":")+1,t=this.refs.input.value.length),t-e===2&&(0,s["default"])(this.refs.input,e,t)}},render:function(){var e=this.props.prefixCls;return i["default"].createElement("div",{className:e+"-input-wrap"},this.getInput(),this.getClearButton())}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e,t,n){for(var r=[],o=0;o<e;o++)(!t||t.indexOf(o)<0||!n)&&r.push(o);return r}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a),l=n(161),u=r(l),c=n(478),p=r(c),f=n(477),d=r(f),h=s["default"].createClass({displayName:"Panel",propTypes:{prefixCls:a.PropTypes.string,value:a.PropTypes.object,locale:a.PropTypes.object,placeholder:a.PropTypes.string,gregorianCalendarLocale:a.PropTypes.object,formatter:a.PropTypes.object,disabledHours:a.PropTypes.func,disabledMinutes:a.PropTypes.func,disabledSeconds:a.PropTypes.func,hideDisabledOptions:a.PropTypes.bool,onChange:a.PropTypes.func,onEsc:a.PropTypes.func,allowEmpty:a.PropTypes.bool,showHour:a.PropTypes.bool,showSecond:a.PropTypes.bool,onClear:a.PropTypes.func},mixins:[u["default"]],getDefaultProps:function(){return{prefixCls:"rc-time-picker-panel",onChange:o,onClear:o}},getInitialState:function(){return{value:this.props.value,selectionRange:[]}},componentWillReceiveProps:function(e){var t=e.value;t&&this.setState({value:t})},onChange:function(e){this.setState({value:e}),this.props.onChange(e)},onClear:function(){this.props.onClear()},onCurrentSelectPanelChange:function(e){this.setState({currentSelectPanel:e})},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.placeholder,o=e.disabledHours,a=e.disabledMinutes,l=e.disabledSeconds,u=e.hideDisabledOptions,c=e.allowEmpty,f=e.showHour,h=e.showSecond,y=e.formatter,v=e.gregorianCalendarLocale,m=this.state.value,g=o(),b=a(m?m.getHourOfDay():null),P=l(m?m.getHourOfDay():null,m?m.getMinutes():null),C=i(24,g,u),T=i(60,b,u),O=i(60,P,u);return s["default"].createElement("div",{className:n+"-inner"},s["default"].createElement(p["default"],{prefixCls:n,gregorianCalendarLocale:v,locale:t,value:m,currentSelectPanel:this.state.currentSelectPanel,onEsc:this.props.onEsc,formatter:y,placeholder:r,hourOptions:C,minuteOptions:T,secondOptions:O,disabledHours:o,disabledMinutes:a,disabledSeconds:l,onChange:this.onChange,onClear:this.onClear,allowEmpty:c}),s["default"].createElement(d["default"],{prefixCls:n,value:m,gregorianCalendarLocale:v,formatter:y,onChange:this.onChange,showHour:f,showSecond:h,hourOptions:C,minuteOptions:T,secondOptions:O,disabledHours:o,disabledMinutes:a,disabledSeconds:l,onCurrentSelectPanelChange:this.onCurrentSelectPanelChange}))}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=n(4),l=r(s),u=n(2),c=r(u),p=function d(e,t,n){var r=window.requestAnimationFrame||function(){return setTimeout(arguments[0],10)};if(n<=0)return void(e.scrollTop=t);var o=t-e.scrollTop,i=o/n*10;r(function(){e.scrollTop=e.scrollTop+i,e.scrollTop!==t&&d(e,t,n-10)})},f=a["default"].createClass({displayName:"Select",propTypes:{prefixCls:i.PropTypes.string,options:i.PropTypes.array,gregorianCalendarLocale:i.PropTypes.object,selectedIndex:i.PropTypes.number,type:i.PropTypes.string,onSelect:i.PropTypes.func,onMouseEnter:i.PropTypes.func},componentDidMount:function(){this.scrollToSelected(0)},componentDidUpdate:function(e){e.selectedIndex!==this.props.selectedIndex&&this.scrollToSelected(120)},onSelect:function h(e){var t=this.props,h=t.onSelect,n=t.type;h(n,e)},getOptions:function(){var e=this,t=this.props,n=t.options,r=t.selectedIndex,i=t.prefixCls;return n.map(function(t,n){var s,l=(0,c["default"])((s={},o(s,i+"-select-option-selected",r===n),o(s,i+"-select-option-disabled",t.disabled),s)),u=null;return t.disabled||(u=e.onSelect.bind(e,+t.value)),a["default"].createElement("li",{className:l,key:n,onClick:u,disabled:t.disabled},t.value)})},scrollToSelected:function(e){var t=l["default"].findDOMNode(this),n=l["default"].findDOMNode(this.refs.list),r=this.props.selectedIndex;r<0&&(r=0);var o=n.children[r],i=o.offsetTop;p(t,i,e)},render:function(){if(0===this.props.options.length)return null;var e=this.props.prefixCls;return a["default"].createElement("div",{className:e+"-select",onMouseEnter:this.props.onMouseEnter},a["default"].createElement("ul",{ref:"list"},this.getOptions()))}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return"string"==typeof e?new a["default"](e,t.format):e}Object.defineProperty(t,"__esModule",{value:!0}),t.getFormatter=o;var i=n(53),a=r(i)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o={bottomLeft:{points:["tl","tl"],overflow:n,offset:[0,-3],targetOffset:r},bottomRight:{points:["tr","tr"],overflow:n,offset:[0,-3],targetOffset:r},topRight:{points:["br","br"],overflow:n,offset:[0,3],targetOffset:r},topLeft:{points:["bl","bl"],overflow:n,offset:[0,3],targetOffset:r}};t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(e,t,n){if(e.createTextRange){var r=e.createTextRange();r.collapse(!0),r.moveStart("character",t),r.moveEnd("character",n),r.select(),e.focus()}else e.setSelectionRange?(e.focus(),e.setSelectionRange(t,n)):"undefined"!=typeof e.selectionStart&&(e.selectionStart=t,e.selectionEnd=n,e.focus())}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),s=r(a),l=n(163),u=n(28),c=r(u),p=s["default"].createClass({displayName:"Tooltip",propTypes:{trigger:a.PropTypes.any,children:a.PropTypes.any,defaultVisible:a.PropTypes.bool,visible:a.PropTypes.bool,placement:a.PropTypes.string,transitionName:a.PropTypes.string,animation:a.PropTypes.any,onVisibleChange:a.PropTypes.func, afterVisibleChange:a.PropTypes.func,overlay:a.PropTypes.oneOfType([s["default"].PropTypes.node,s["default"].PropTypes.func]).isRequired,overlayStyle:a.PropTypes.object,overlayClassName:a.PropTypes.string,prefixCls:a.PropTypes.string,mouseEnterDelay:a.PropTypes.number,mouseLeaveDelay:a.PropTypes.number,getTooltipContainer:a.PropTypes.func,destroyTooltipOnHide:a.PropTypes.bool,align:a.PropTypes.object,arrowContent:a.PropTypes.any},getDefaultProps:function(){return{prefixCls:"rc-tooltip",mouseEnterDelay:0,destroyTooltipOnHide:!1,mouseLeaveDelay:.1,align:{},placement:"right",trigger:["hover"],arrowContent:null}},getPopupElement:function(){var e=this.props,t=e.arrowContent,n=e.overlay,r=e.prefixCls;return[s["default"].createElement("div",{className:r+"-arrow",key:"arrow"},t),s["default"].createElement("div",{className:r+"-inner",key:"content"},"function"==typeof n?n():n)]},getPopupDomNode:function(){return this.refs.trigger.getPopupDomNode()},render:function(){var e=this.props,t=e.overlayClassName,n=e.trigger,r=e.mouseEnterDelay,a=e.mouseLeaveDelay,u=e.overlayStyle,p=e.prefixCls,f=e.children,d=e.onVisibleChange,h=e.transitionName,y=e.animation,v=e.placement,m=e.align,g=e.destroyTooltipOnHide,b=e.defaultVisible,P=e.getTooltipContainer,C=o(e,["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","children","onVisibleChange","transitionName","animation","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer"]),T=i({},C);return"visible"in this.props&&(T.popupVisible=this.props.visible),s["default"].createElement(c["default"],i({popupClassName:t,ref:"trigger",prefixCls:p,popup:this.getPopupElement,action:n,builtinPlacements:l.placements,popupPlacement:v,popupAlign:m,getPopupContainer:P,onPopupVisibleChange:d,popupTransitionName:h,popupAnimation:y,defaultPopupVisible:b,destroyPopupOnHide:g,mouseLeaveDelay:a,popupStyle:u,mouseEnterDelay:r},T),f)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(){}function s(e,t){return String((0,O.getPropValue)(t,(0,O.labelCompatible)(this.props.treeNodeFilterProp))).indexOf(e)>-1}function l(e,t){this[e]=t}function u(e){var t=arguments.length<=1||void 0===arguments[1]?0:arguments[1];return e.map(function(e,n){var r=t+"-"+n,o={title:e.label,value:e.value,key:e.key||e.value||r,disabled:e.disabled||!1,selectable:!e.hasOwnProperty("selectable")||e.selectable},i=void 0;return i=e.children&&e.children.length?f["default"].createElement(S["default"],o,u(e.children,r)):f["default"].createElement(S["default"],c({},o,{isLeaf:e.isLeaf}))})}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(4),h=r(d),y=n(15),v=r(y),m=n(2),g=r(m),b=n(10),P=r(b),C=n(9),T=r(C),O=n(165),w=n(486),x=r(w),E=n(164),S=r(E),k="SHOW_ALL",N="SHOW_PARENT",j="SHOW_CHILD",_=f["default"].createClass({displayName:"Select",propTypes:{children:p.PropTypes.any,className:p.PropTypes.string,prefixCls:p.PropTypes.string,multiple:p.PropTypes.bool,filterTreeNode:p.PropTypes.any,showSearch:p.PropTypes.bool,disabled:p.PropTypes.bool,showArrow:p.PropTypes.bool,allowClear:p.PropTypes.bool,defaultOpen:p.PropTypes.bool,open:p.PropTypes.bool,transitionName:p.PropTypes.string,animation:p.PropTypes.string,choiceTransitionName:p.PropTypes.string,onClick:p.PropTypes.func,onChange:p.PropTypes.func,onSelect:p.PropTypes.func,onDeselect:p.PropTypes.func,onSearch:p.PropTypes.func,searchPlaceholder:p.PropTypes.string,placeholder:p.PropTypes.any,inputValue:p.PropTypes.any,value:p.PropTypes.oneOfType([p.PropTypes.array,p.PropTypes.string,p.PropTypes.object]),defaultValue:p.PropTypes.oneOfType([p.PropTypes.array,p.PropTypes.string,p.PropTypes.object]),label:p.PropTypes.any,defaultLabel:p.PropTypes.any,labelInValue:p.PropTypes.bool,dropdownStyle:p.PropTypes.object,drodownPopupAlign:p.PropTypes.object,onDropdownVisibleChange:p.PropTypes.func,maxTagTextLength:p.PropTypes.number,showCheckedStrategy:p.PropTypes.oneOf([k,N,j]),treeCheckStrictly:p.PropTypes.bool,treeIcon:p.PropTypes.bool,treeLine:p.PropTypes.bool,treeDefaultExpandAll:p.PropTypes.bool,treeCheckable:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.node]),treeNodeLabelProp:p.PropTypes.string,treeNodeFilterProp:p.PropTypes.string,treeData:p.PropTypes.array,treeDataSimpleMode:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.object]),loadData:p.PropTypes.func},getDefaultProps:function(){return{prefixCls:"rc-tree-select",filterTreeNode:s,showSearch:!0,allowClear:!1,placeholder:"",searchPlaceholder:"",labelInValue:!1,defaultValue:[],inputValue:"",onClick:a,onChange:a,onSelect:a,onDeselect:a,onSearch:a,showArrow:!0,dropdownMatchSelectWidth:!0,dropdownStyle:{},onDropdownVisibleChange:function(){return!0},notFoundContent:"Not Found",showCheckedStrategy:j,treeCheckStrictly:!1,treeIcon:!1,treeLine:!1,treeDataSimpleMode:!1,treeDefaultExpandAll:!1,treeCheckable:!1,treeNodeFilterProp:"value",treeNodeLabelProp:"title"}},getInitialState:function(){var e=this.props,t=[];t="value"in e?(0,O.toArray)(e.value):(0,O.toArray)(e.defaultValue),this.renderedTreeData=this.renderTreeData(),t=this.addLabelToValue(e,t),t=this.getValue(e,t,!e.inputValue||"__strict");var n=e.inputValue||"";return this.saveInputRef=l.bind(this,"inputInstance"),{value:t,inputValue:n,open:e.open||e.defaultOpen,focused:!1}},componentDidMount:function(){if(this.state.inputValue){var e=this.getInputDOMNode();e&&e.value&&(e.style.width="",e.style.width=e.scrollWidth+"px")}},componentWillReceiveProps:function(e){if(this.renderedTreeData=this.renderTreeData(e),"value"in e){"no"!==this._cacheTreeNodesStates&&this._savedValue&&e.value===this._savedValue?this._cacheTreeNodesStates=!0:this._cacheTreeNodesStates=!1;var t=(0,O.toArray)(e.value);t=this.addLabelToValue(e,t),t=this.getValue(e,t),this.setState({value:t})}e.inputValue!==this.props.inputValue&&this.setState({inputValue:e.inputValue}),"open"in e&&this.setState({open:e.open})},componentWillUpdate:function(e){this._savedValue&&e.value&&e.value!==this._savedValue&&e.value===this.props.value&&(this._cacheTreeNodesStates=!1,this.getValue(e,this.addLabelToValue(e,(0,O.toArray)(e.value))))},componentDidUpdate:function(){var e=this.state,t=this.props;if(e.open&&(0,O.isMultipleOrTags)(t)){var n=this.getInputDOMNode();n.value?(n.style.width="",n.style.width=n.scrollWidth+"px"):n.style.width=""}},componentWillUnmount:function(){this.clearDelayTimer(),this.dropdownContainer&&(h["default"].unmountComponentAtNode(this.dropdownContainer),document.body.removeChild(this.dropdownContainer),this.dropdownContainer=null)},onInputChange:function(e){var t=e.target.value,n=this.props;this.setState({inputValue:t,open:!0}),n.treeCheckable&&!t&&this.setState({value:this.getValue(n,[].concat(i(this.state.value)),!1)}),n.onSearch(t)},onDropdownVisibleChange:function(e){var t=this;!e&&document.activeElement===this.getInputDOMNode(),setTimeout(function(){t.setOpenState(e,void 0,!e)},10)},onKeyDown:function(e){var t=this.props;if(!t.disabled){var n=e.keyCode;this.state.open&&!this.getInputDOMNode()?this.onInputKeyDown(e):n!==v["default"].ENTER&&n!==v["default"].DOWN||(this.setOpenState(!0),e.preventDefault())}},onInputBlur:function(){},onInputKeyDown:function(e){var t=this.props;if(!t.disabled){var n=this.state,r=e.keyCode;if(!(0,O.isMultipleOrTags)(t)||e.target.value||r!==v["default"].BACKSPACE){if(r===v["default"].DOWN){if(!n.open)return this.openIfHasChildren(),e.preventDefault(),void e.stopPropagation()}else if(r===v["default"].ESC)return void(n.open&&(this.setOpenState(!1),e.preventDefault(),e.stopPropagation()));n.open}else{var o=n.value.concat();if(o.length){var i=o.pop();t.onDeselect(this.isLabelInValue()?i:i.key),this.fireChange(o)}}}},onSelect:function(e,t){var n=this;if(t.selected===!1)return void this.onDeselect(t);var r=t.node,o=this.state.value,i=this.props,a=(0,O.getValuePropValue)(r),s=this.getLabelFromNode(r),l=a;this.isLabelInValue()&&(l={value:l,label:s}),i.onSelect(l,r,t);var u="check"===t.event;if((0,O.isMultipleOrTags)(i))if(u)o=this.getCheckedNodes(t,i).map(function(e){return{value:(0,O.getValuePropValue)(e),label:n.getLabelFromNode(e)}});else{if(o.some(function(e){return e.value===a}))return;o=o.concat([{value:a,label:s}])}else{if(o.length&&o[0].value===a)return void this.setOpenState(!1);o=[{value:a,label:s}],this.setOpenState(!1)}var c={triggerValue:a,triggerNode:r};if(u){c.checked=t.checked,c.allCheckedNodes=i.treeCheckStrictly||this.state.inputValue?t.checkedNodes:(0,O.flatToHierarchy)(t.checkedNodesPositions),this._checkedNodes=t.checkedNodesPositions;var p=this.refs.trigger.popupEle;this._treeNodesStates=p.checkKeys}else c.selected=t.selected;this.fireChange(o,c),null===i.inputValue&&this.setState({inputValue:""})},onDeselect:function(e){this.removeSelected((0,O.getValuePropValue)(e.node)),(0,O.isMultipleOrTags)(this.props)||this.setOpenState(!1),null===this.props.inputValue&&this.setState({inputValue:""})},onPlaceholderClick:function(){this.getInputDOMNode().focus()},onOuterFocus:function(){},onOuterBlur:function(){},onClearSelection:function(e){var t=this.props,n=this.state;t.disabled||(e.stopPropagation(),(n.inputValue||n.value.length)&&(this.fireChange([]),this.setOpenState(!1),null===t.inputValue&&this.setState({inputValue:""})))},getLabelFromNode:function(e){return(0,O.getPropValue)(e,this.props.treeNodeLabelProp)},getLabelFromProps:function(e,t){var n=this;if(void 0===t)return null;var r=null;return(0,O.loopAllChildren)(this.renderedTreeData||e.children,function(e){(0,O.getValuePropValue)(e)===t&&(r=n.getLabelFromNode(e))}),null===r?t:r},getDropdownContainer:function(){return this.dropdownContainer||(this.dropdownContainer=document.createElement("div"),document.body.appendChild(this.dropdownContainer)),this.dropdownContainer},getSearchPlaceholderElement:function(e){var t=this.props,n=void 0;return n=(0,O.isMultipleOrTagsOrCombobox)(t)?t.placeholder||t.searchPlaceholder:t.searchPlaceholder,n?f["default"].createElement("span",{style:{display:e?"none":"block"},onClick:this.onPlaceholderClick,className:t.prefixCls+"-search__field__placeholder"},n):null},getInputElement:function(){var e=this.props;return f["default"].createElement("span",{className:e.prefixCls+"-search__field__wrap"},f["default"].createElement("input",{ref:this.saveInputRef,onBlur:this.onInputBlur,onChange:this.onInputChange,onKeyDown:this.onInputKeyDown,value:this.state.inputValue,disabled:e.disabled,className:e.prefixCls+"-search__field",role:"textbox"}),(0,O.isMultipleOrTags)(e)?null:this.getSearchPlaceholderElement(!!this.state.inputValue))},getInputDOMNode:function(){return this.inputInstance},getPopupDOMNode:function(){return this.refs.trigger.getPopupDOMNode()},getPopupComponentRefs:function(){return this.refs.trigger.getPopupEleRefs()},getValue:function(e,t){var n=this,r=arguments.length<=2||void 0===arguments[2]||arguments[2],o=t,i="__strict"===r||r&&(this.state&&this.state.inputValue||this.props.inputValue!==e.inputValue);if(e.treeCheckable&&(e.treeCheckStrictly||i)&&(this.halfCheckedValues=[],o=[],t.forEach(function(e){e.halfChecked?n.halfCheckedValues.push(e):o.push(e)})),!e.treeCheckable||e.treeCheckable&&(e.treeCheckStrictly||i))return o;var a=void 0;this._cachetreeData&&this._cacheTreeNodesStates&&this._checkedNodes&&this.state&&!this.state.inputValue?this.checkedTreeNodes=a=this._checkedNodes:(this._treeNodesStates=(0,O.getTreeNodesStates)(this.renderedTreeData||e.children,o.map(function(e){return e.value})),this.checkedTreeNodes=a=this._treeNodesStates.checkedNodes);var s=function(t){return t.map(function(t){return{value:(0,O.getValuePropValue)(t.node),label:(0,O.getPropValue)(t.node,e.treeNodeLabelProp)}})},l=this.props,u=[];return l.showCheckedStrategy===k?u=s(a):l.showCheckedStrategy===N?!function(){var e=(0,O.filterParentPosition)(a.map(function(e){return e.pos}));u=s(a.filter(function(t){return e.indexOf(t.pos)!==-1}))}():u=s(a.filter(function(e){return!e.node.props.children})),u},getCheckedNodes:function(e,t){var n=e.checkedNodes;if(t.treeCheckStrictly||this.state.inputValue)return n;var r=e.checkedNodesPositions;return t.showCheckedStrategy===k?n=n:t.showCheckedStrategy===N?!function(){var e=(0,O.filterParentPosition)(r.map(function(e){return e.pos}));n=r.filter(function(t){return e.indexOf(t.pos)!==-1}).map(function(e){return e.node})}():n=n.filter(function(e){return!e.props.children}),n},getDeselectedValue:function(e){var t=this.checkedTreeNodes,n=void 0;t.forEach(function(t){t.node.props.value===e&&(n=t.pos)});var r=n.split("-"),o=[],i=[];t.forEach(function(e){var t=e.pos.split("-");e.pos===n||r.length>t.length&&(0,O.isInclude)(t,r)||r.length<t.length&&(0,O.isInclude)(r,t)||(i.push(e),o.push(e.node.props.value))}),this.checkedTreeNodes=this._checkedNodes=i;var a=this.state.value.filter(function(e){return o.indexOf(e.value)!==-1});this.fireChange(a,{triggerValue:e,clear:!0})},setOpenState:function(e,t){var n=this,r=!(arguments.length<=2||void 0===arguments[2])&&arguments[2];this.clearDelayTimer();var o=this.props,i=this.refs;this.props.onDropdownVisibleChange(e,{documentClickClose:r})&&this.setState({open:e},function(){if(t||e)if(e||(0,O.isMultipleOrTagsOrCombobox)(o)){var r=n.getInputDOMNode();r&&document.activeElement!==r&&r.focus()}else i.selection&&i.selection.focus()})},addLabelToValue:function(e,t){var n=this,r=t;return this.isLabelInValue()?r.forEach(function(t,o){return"[object Object]"!==Object.prototype.toString.call(r[o])?void(r[o]={value:"",label:""}):void(t.label=t.label||n.getLabelFromProps(e,t.value))}):r=r.map(function(t){return{value:t,label:n.getLabelFromProps(e,t)}}),r},clearDelayTimer:function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},removeSelected:function(e){var t=this.props;if(!t.disabled){if(this._cacheTreeNodesStates="no",t.treeCheckable&&(t.showCheckedStrategy===k||t.showCheckedStrategy===N)&&!t.treeCheckStrictly&&!this.state.inputValue)return void this.getDeselectedValue(e);var n=void 0,r=this.state.value.filter(function(t){return t.value===e&&(n=t.label),t.value!==e}),o=(0,O.isMultipleOrTags)(t);if(o){var i=e;this.isLabelInValue()&&(i={value:e,label:n}),t.onDeselect(i)}t.treeCheckable&&this.checkedTreeNodes&&this.checkedTreeNodes.length&&(this.checkedTreeNodes=this._checkedNodes=this.checkedTreeNodes.filter(function(e){return r.some(function(t){return t.value===e.node.props.value})})),this.fireChange(r,{triggerValue:e,clear:!0})}},openIfHasChildren:function(){var e=this.props;(f["default"].Children.count(e.children)||(0,O.isSingleMode)(e))&&this.setOpenState(!0)},fireChange:function(e,t){var n=this,r=this.props,o=e.map(function(e){return e.value}),a=this.state.value.map(function(e){return e.value});o.length===a.length&&o.every(function(e,t){return a[t]===e})||!function(){var a={preValue:[].concat(i(n.state.value))};t&&(0,P["default"])(a,t);var s=null,l=e;if(n.isLabelInValue()?n.halfCheckedValues&&n.halfCheckedValues.length&&n.halfCheckedValues.forEach(function(e){l.some(function(t){return t.value===e.value})||l.push(e)}):(s=e.map(function(e){return e.label}),l=l.map(function(e){return e.value})),r.treeCheckable&&a.clear){var u=n.renderedTreeData||r.children;a.allCheckedNodes=(0,O.flatToHierarchy)((0,O.filterAllCheckedData)(o,u))}r.treeCheckable&&n.state.inputValue&&!function(){var t=[].concat(i(n.state.value));if(a.checked)e.forEach(function(e){t.every(function(t){return t.value!==e.value})&&t.push(c({},e))});else{var r=void 0,o=t.some(function(e,t){if(e.value===a.triggerValue)return r=t,!0});o&&t.splice(r,1)}l=t,n.isLabelInValue()||(s=t.map(function(e){return e.label}),l=t.map(function(e){return e.value}))}(),n._savedValue=(0,O.isMultipleOrTags)(r)?l:l[0],r.onChange(n._savedValue,s,a),"value"in r||(n._cacheTreeNodesStates=!1,n.setState({value:n.getValue(r,(0,O.toArray)(n._savedValue).map(function(e,t){return{value:e,label:s[t]}}))}))}()},isLabelInValue:function(){var e=this.props,t=e.treeCheckable,n=e.treeCheckStrictly,r=e.labelInValue;return!(!t||!n)||(r||!1)},renderTopControlNode:function(){var e=this,t=this.state.value,n=this.props,r=n.choiceTransitionName,o=n.prefixCls,i=n.maxTagTextLength;if((0,O.isSingleMode)(n)){var a=f["default"].createElement("span",{key:"placeholder",className:o+"-selection__placeholder"},n.placeholder);return t.length&&(a=f["default"].createElement("span",{key:"value"},t[0].label)),f["default"].createElement("span",{className:o+"-selection__rendered"},a)}var s=[];(0,O.isMultipleOrTags)(n)&&(s=t.map(function(t){var n=t.label,r=n;return i&&"string"==typeof n&&n.length>i&&(n=n.slice(0,i)+"..."),f["default"].createElement("li",c({style:O.UNSELECTABLE_STYLE},O.UNSELECTABLE_ATTRIBUTE,{onMouseDown:O.preventDefaultEvent,className:o+"-selection__choice",key:t.value,title:r}),f["default"].createElement("span",{className:o+"-selection__choice__remove",onClick:e.removeSelected.bind(e,t.value)}),f["default"].createElement("span",{className:o+"-selection__choice__content"},n))})),s.push(f["default"].createElement("li",{className:o+"-search "+o+"-search--inline",key:"__input"},this.getInputElement()));var l=o+"-selection__rendered";return(0,O.isMultipleOrTags)(n)&&r?f["default"].createElement(T["default"],{className:l,component:"ul",transitionName:r},s):f["default"].createElement("ul",{className:l},s)},renderTreeData:function(e){var t=e||this.props;if(t.treeData){if(e&&e.treeData===this.props.treeData&&this.renderedTreeData)return this._cachetreeData=!0,this.renderedTreeData;this._cachetreeData=!1;var n=[].concat(i(t.treeData));if(t.treeDataSimpleMode){var r={id:"id",pId:"pId",rootPId:null};"[object Object]"===Object.prototype.toString.call(t.treeDataSimpleMode)&&(0,P["default"])(r,t.treeDataSimpleMode),n=(0,O.processSimpleTreeData)(n,r)}return u(n)}},render:function(){var e,t=this.props,n=(0,O.isMultipleOrTags)(t),r=this.state,i=t.className,a=t.disabled,s=t.allowClear,l=t.prefixCls,u=this.renderTopControlNode(),p={};(0,O.isMultipleOrTagsOrCombobox)(t)||(p={onKeyDown:this.onKeyDown,tabIndex:0});var d=(e={},o(e,i,!!i),o(e,l,1),o(e,l+"-open",r.open),o(e,l+"-focused",r.open||r.focused),o(e,l+"-disabled",a),o(e,l+"-enabled",!a),e),h=f["default"].createElement("span",{key:"clear",className:l+"-selection__clear",onClick:this.onClearSelection});return f["default"].createElement(x["default"],c({},t,{treeNodes:t.children,treeData:this.renderedTreeData,_cachetreeData:this._cachetreeData,_treeNodesStates:this._treeNodesStates,halfCheckedValues:this.halfCheckedValues,multiple:n,disabled:a,visible:r.open,inputValue:r.inputValue,inputElement:this.getInputElement(),value:r.value,onDropdownVisibleChange:this.onDropdownVisibleChange,getPopupContainer:t.getPopupContainer,onSelect:this.onSelect,ref:"trigger"}),f["default"].createElement("span",{style:t.style,onClick:t.onClick,onBlur:this.onOuterBlur,onFocus:this.onOuterFocus,className:(0,g["default"])(d)},f["default"].createElement("span",c({ref:"selection",key:"selection",className:l+"-selection\n "+l+"-selection--"+(n?"multiple":"single"),role:"combobox","aria-autocomplete":"list","aria-haspopup":"true","aria-expanded":r.open},p),u,s&&!n&&this.state.value.length&&this.state.value[0].value?h:null,n||!t.showArrow?null:f["default"].createElement("span",{key:"arrow",className:l+"-arrow",style:{outline:"none"}},f["default"].createElement("b",null)),n?this.getSearchPlaceholderElement(!!this.state.inputValue||this.state.value.length):null)))}});_.SHOW_ALL=k,_.SHOW_PARENT=N,_.SHOW_CHILD=j,t["default"]=_,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),s=r(a),l=n(4),u=r(l),c=n(2),p=r(c),f=n(28),d=r(f),h=n(166),y=r(h),v=n(165),m=n(500),g=r(m),b={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:0,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:0,adjustY:1}}},P=s["default"].createClass({displayName:"SelectTrigger",propTypes:{dropdownMatchSelectWidth:a.PropTypes.bool,dropdownPopupAlign:a.PropTypes.object,visible:a.PropTypes.bool,filterTreeNode:a.PropTypes.any,treeNodes:a.PropTypes.any,inputValue:a.PropTypes.string,prefixCls:a.PropTypes.string,popupClassName:a.PropTypes.string,children:a.PropTypes.any},getInitialState:function(){return{_expandedKeys:[],fireOnExpand:!1}},componentWillReceiveProps:function(e){e.inputValue&&e.inputValue!==this.props.inputValue&&this.setState({_expandedKeys:[],fireOnExpand:!1})},componentDidUpdate:function(){if(this.props.dropdownMatchSelectWidth&&this.props.visible){var e=this.getPopupDOMNode();e&&(e.style.width=u["default"].findDOMNode(this).offsetWidth+"px")}},onExpand:function(e){this.setState({_expandedKeys:e,fireOnExpand:!0})},getPopupEleRefs:function(){return this.popupEle&&this.popupEle.refs},getPopupDOMNode:function(){return this.refs.trigger.getPopupDomNode()},getDropdownTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=this.getDropdownPrefixCls()+"-"+e.animation),t},getDropdownPrefixCls:function(){return this.props.prefixCls+"-dropdown"},highlightTreeNode:function(e){var t=this.props,n=e.props[(0,v.labelCompatible)(t.treeNodeFilterProp)];return"string"==typeof n&&(t.inputValue&&n.indexOf(t.inputValue)>-1)},filterTreeNode:function C(e,t){if(!e)return!0;var C=this.props.filterTreeNode;return!C||!t.props.disabled&&C.call(this,e,t)},savePopupElement:function(e){this.popupEle=e},processTreeNode:function(e){var t=this,n=[];this._expandedKeys=[],(0,v.loopAllChildren)(e,function(e,r,o){t.filterTreeNode(t.props.inputValue,e)&&(n.push(o),t._expandedKeys.push(e.key))});var r=[];n.forEach(function(e){var t=e.split("-");t.reduce(function(e,t){var n=e+"-"+t;return r.indexOf(n)<0&&r.push(n),n})});var o=[];(0,v.loopAllChildren)(e,function(e,t,n){r.indexOf(n)>-1&&o.push({node:e,pos:n})});var i=(0,v.flatToHierarchy)(o),a=function l(e){return e.map(function(e){return e.children?s["default"].cloneElement(e.node,{},l(e.children)):e.node})};return a(i)},renderTree:function(e,t,n,r){var o=this.props,a={multiple:r,prefixCls:o.prefixCls+"-tree",showIcon:o.treeIcon,showLine:o.treeLine,defaultExpandAll:o.treeDefaultExpandAll,filterTreeNode:this.highlightTreeNode};return o.treeCheckable?(a.selectable=!1,a.checkable=o.treeCheckable,a.onCheck=o.onSelect,a.checkStrictly=o.treeCheckStrictly,o.inputValue?a.checkStrictly=!0:a._treeNodesStates=o._treeNodesStates,a.treeCheckStrictly&&t.length?a.checkedKeys={checked:e,halfChecked:t}:a.checkedKeys=e):(a.selectedKeys=e,a.onSelect=o.onSelect),a.defaultExpandAll||o.loadData||(a.expandedKeys=e),a.autoExpandParent=!0,a.onExpand=this.onExpand,this._expandedKeys&&this._expandedKeys.length&&(a.expandedKeys=this._expandedKeys),this.state.fireOnExpand&&(a.expandedKeys=this.state._expandedKeys,a.autoExpandParent=!1),o.loadData&&(a.loadData=o.loadData),s["default"].createElement(y["default"],i({ref:this.savePopupElement},a),n)},render:function(){var e,t=this.props,n=t.multiple,r=this.getDropdownPrefixCls(),a=(e={},o(e,t.dropdownClassName,!!t.dropdownClassName),o(e,r+"--"+(n?"multiple":"single"),1),e),l=t.visible,u=n||t.combobox||!t.showSearch?null:s["default"].createElement("span",{className:r+"-search"},t.inputElement),c=function T(e){return(0,g["default"])(e).map(function(e){return e&&e.props.children?s["default"].createElement(h.TreeNode,i({},e.props,{key:e.key}),T(e.props.children)):s["default"].createElement(h.TreeNode,i({},e.props,{key:e.key}))})},f=void 0;t._cachetreeData&&this.treeNodes?f=this.treeNodes:(f=c(t.treeData||t.treeNodes),this.treeNodes=f),t.inputValue&&(f=this.processTreeNode(f));var y=[],m=[];(0,v.loopAllChildren)(f,function(e){t.value.some(function(t){return t.value===(0,v.getValuePropValue)(e)})&&y.push(e.key),t.halfCheckedValues&&t.halfCheckedValues.some(function(t){return t.value===(0,v.getValuePropValue)(e)})&&m.push(e.key)});var P=void 0;f.length||(t.notFoundContent?P=s["default"].createElement("span",{className:t.prefixCls+"-not-found"},t.notFoundContent):u||(l=!1));var C=s["default"].createElement("div",null,u,P||this.renderTree(y,m,f,n));return s["default"].createElement(d["default"],{action:t.disabled?[]:["click"],ref:"trigger",popupPlacement:"bottomLeft",builtinPlacements:b,popupAlign:t.dropdownPopupAlign,prefixCls:r,popupTransitionName:this.getDropdownTransitionName(),onPopupVisibleChange:t.onDropdownVisibleChange,popup:C,popupVisible:l,getPopupContainer:t.getPopupContainer,popupClassName:(0,p["default"])(a),popupStyle:t.dropdownStyle},this.props.children)}});t["default"]=P,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(485),i=r(o),a=n(164),s=r(a);i["default"].TreeNode=s["default"],t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}function u(){}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(10),h=r(d),y=n(2),v=r(y),m=n(167),g=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return["onKeyDown","onCheck"].forEach(function(e){r[e]=r[e].bind(r)}),r.contextmenuKeys=[],r.checkedKeysChange=!0,r.state={expandedKeys:r.getDefaultExpandedKeys(n),checkedKeys:r.getDefaultCheckedKeys(n),selectedKeys:r.getDefaultSelectedKeys(n),dragNodesKeys:"",dragOverNodeKey:"",dropNodeKey:""},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){var t=this.getDefaultExpandedKeys(e,!0),n=this.getDefaultCheckedKeys(e,!0),r=this.getDefaultSelectedKeys(e,!0),o={};t&&(o.expandedKeys=t),n&&(e.checkedKeys===this.props.checkedKeys?this.checkedKeysChange=!1:this.checkedKeysChange=!0,o.checkedKeys=n),r&&(o.selectedKeys=r),this.setState(o)},t.prototype.onDragStart=function(e,t){this.dragNode=t,this.dragNodesKeys=this.getDragNodes(t);var n={dragNodesKeys:this.dragNodesKeys},r=this.getExpandedKeys(t,!1);r&&(this.getRawExpandedKeys(),n.expandedKeys=r),this.setState(n),this.props.onDragStart({event:e,node:t}),this._dropTrigger=!1},t.prototype.onDragEnterGap=function(e,t){var n=(0,m.getOffset)(t.refs.selectHandle).top,r=t.refs.selectHandle.offsetHeight,o=e.pageY,i=2;return o>n+r-i?(this.dropPosition=1,1):o<n+i?(this.dropPosition=-1,-1):(this.dropPosition=0,0)},t.prototype.onDragEnter=function(e,t){var n=this.onDragEnterGap(e,t);if(this.dragNode.props.eventKey===t.props.eventKey&&0===n)return void this.setState({dragOverNodeKey:""});var r={dragOverNodeKey:t.props.eventKey},o=this.getExpandedKeys(t,!0);o&&(this.getRawExpandedKeys(),r.expandedKeys=o),this.setState(r),this.props.onDragEnter({event:e,node:t,expandedKeys:o&&[].concat(i(o))||[].concat(i(this.state.expandedKeys))})},t.prototype.onDragOver=function(e,t){this.props.onDragOver({event:e,node:t})},t.prototype.onDragLeave=function(e,t){this.props.onDragLeave({event:e,node:t})},t.prototype.onDrop=function(e,t){var n=t.props.eventKey;if(this.setState({dragOverNodeKey:"",dropNodeKey:n}),this.dragNodesKeys.indexOf(n)>-1)return console.warn&&console.warn("can not drop to dragNode(include it's children node)"),!1;var r=t.props.pos.split("-"),o={event:e,node:t,dragNode:this.dragNode,dragNodesKeys:[].concat(i(this.dragNodesKeys)),dropPosition:this.dropPosition+Number(r[r.length-1])};0!==this.dropPosition&&(o.dropToGap=!0),"expandedKeys"in this.props&&(o.rawExpandedKeys=[].concat(i(this._rawExpandedKeys))||[].concat(i(this.state.expandedKeys))),this.props.onDrop(o),this._dropTrigger=!0},t.prototype.onExpand=function(e){var t=this,n=!e.props.expanded,r="expandedKeys"in this.props,o=[].concat(i(this.state.expandedKeys)),a=o.indexOf(e.props.eventKey);if(n&&a===-1?o.push(e.props.eventKey):!n&&a>-1&&o.splice(a,1),r||this.setState({expandedKeys:o}),this.props.onExpand(o,{node:e,expanded:n}),n&&this.props.loadData)return this.props.loadData(e).then(function(){r||t.setState({expandedKeys:o})})},t.prototype.onCheck=function(e){var t=this,n=!e.props.checked;e.props.halfChecked&&(n=!0);var r=e.props.eventKey,o=[].concat(i(this.state.checkedKeys)),a=o.indexOf(r),s={event:"check",node:e,checked:n};if(this.props.checkStrictly&&"checkedKeys"in this.props)n&&a===-1&&o.push(r),!n&&a>-1&&o.splice(a,1),s.checkedNodes=[],(0,m.loopAllChildren)(this.props.children,function(e,t,n,r){o.indexOf(r)!==-1&&s.checkedNodes.push(e)}),this.props.onCheck((0,m.getStrictlyValue)(o,this.props.checkedKeys.halfChecked),s);else{n&&a===-1&&!function(){t.treeNodesStates[e.props.pos].checked=!0;var n=[];Object.keys(t.treeNodesStates).forEach(function(e){t.treeNodesStates[e].checked&&n.push(e)}),(0,m.handleCheckState)(t.treeNodesStates,(0,m.filterParentPosition)(n),!0)}(),n||(this.treeNodesStates[e.props.pos].checked=!1,this.treeNodesStates[e.props.pos].halfChecked=!1,(0,m.handleCheckState)(this.treeNodesStates,[e.props.pos],!1));var l=(0,m.getCheck)(this.treeNodesStates);s.checkedNodes=l.checkedNodes,s.checkedNodesPositions=l.checkedNodesPositions,s.halfCheckedKeys=l.halfCheckedKeys,this.checkKeys=l,this._checkedKeys=o=l.checkedKeys,"checkedKeys"in this.props||this.setState({checkedKeys:o}),this.props.onCheck(o,s)}},t.prototype.onSelect=function(e){var t=this.props,n=[].concat(i(this.state.selectedKeys)),r=e.props.eventKey,o=n.indexOf(r),a=void 0;o!==-1?(a=!1,n.splice(o,1)):(a=!0,t.multiple||(n.length=0),n.push(r));var s=[];n.length&&(0,m.loopAllChildren)(this.props.children,function(e){n.indexOf(e.key)!==-1&&s.push(e)});var l={event:"select",node:e,selected:a,selectedNodes:s};"selectedKeys"in this.props||this.setState({selectedKeys:n}),t.onSelect(n,l)},t.prototype.onMouseEnter=function(e,t){this.props.onMouseEnter({event:e,node:t})},t.prototype.onMouseLeave=function(e,t){this.props.onMouseLeave({event:e,node:t})},t.prototype.onContextMenu=function(e,t){var n=[].concat(i(this.state.selectedKeys)),r=t.props.eventKey;this.contextmenuKeys.indexOf(r)===-1&&this.contextmenuKeys.push(r),this.contextmenuKeys.forEach(function(e){var t=n.indexOf(e);t!==-1&&n.splice(t,1)}),n.indexOf(r)===-1&&n.push(r),this.setState({selectedKeys:n}),this.props.onRightClick({event:e,node:t})},t.prototype.onKeyDown=function(e){e.preventDefault()},t.prototype.getFilterExpandedKeys=function(e,t,n){var r=e[t];if(!n&&!e.autoExpandParent)return r||[];var o=[];e.autoExpandParent&&(0,m.loopAllChildren)(e.children,function(e,t,n,i){r.indexOf(i)>-1&&o.push(n)});var i=[];return(0, m.loopAllChildren)(e.children,function(t,r,a,s){n?i.push(s):e.autoExpandParent&&o.forEach(function(e){(e.split("-").length>a.split("-").length&&(0,m.isInclude)(a.split("-"),e.split("-"))||a===e)&&i.indexOf(s)===-1&&i.push(s)})}),i.length?i:r},t.prototype.getDefaultExpandedKeys=function(e,t){var n=t?void 0:this.getFilterExpandedKeys(e,"defaultExpandedKeys",!e.defaultExpandedKeys.length&&e.defaultExpandAll);return"expandedKeys"in e&&(n=(e.autoExpandParent?this.getFilterExpandedKeys(e,"expandedKeys",!1):e.expandedKeys)||[]),n},t.prototype.getDefaultCheckedKeys=function(e,t){var n=t?void 0:e.defaultCheckedKeys;return"checkedKeys"in e&&(n=e.checkedKeys||[],e.checkStrictly&&(e.checkedKeys.checked?n=e.checkedKeys.checked:Array.isArray(e.checkedKeys)||(n=[]))),n},t.prototype.getDefaultSelectedKeys=function(e,t){var n=function(t){return e.multiple?[].concat(i(t)):t.length?[t[0]]:t},r=t?void 0:n(e.defaultSelectedKeys);return"selectedKeys"in e&&(r=n(e.selectedKeys)),r},t.prototype.getRawExpandedKeys=function(){!this._rawExpandedKeys&&"expandedKeys"in this.props&&(this._rawExpandedKeys=[].concat(i(this.state.expandedKeys)))},t.prototype.getOpenTransitionName=function(){var e=this.props,t=e.openTransitionName,n=e.openAnimation;return t||"string"!=typeof n||(t=e.prefixCls+"-open-"+n),t},t.prototype.getDragNodes=function(e){var t=[],n=e.props.pos.split("-");return(0,m.loopAllChildren)(this.props.children,function(r,o,i,a){var s=i.split("-");(e.props.pos===i||n.length<s.length&&(0,m.isInclude)(n,s))&&t.push(a)}),t},t.prototype.getExpandedKeys=function(e,t){var n=e.props.eventKey,r=this.state.expandedKeys,o=r.indexOf(n),a=void 0;return o>-1&&!t?(a=[].concat(i(r)),a.splice(o,1),a):t&&r.indexOf(n)===-1?r.concat([n]):void 0},t.prototype.filterTreeNode=function n(e){var n=this.props.filterTreeNode;return"function"==typeof n&&!e.props.disabled&&n.call(this,e)},t.prototype.renderTreeNode=function(e,t){var n=arguments.length<=2||void 0===arguments[2]?0:arguments[2],r=n+"-"+t,o=e.key||r,i=this.state,a=this.props,s=a.selectable;e.props.hasOwnProperty("selectable")&&(s=e.props.selectable);var l={ref:"treeNode-"+o,root:this,eventKey:o,pos:r,selectable:s,loadData:a.loadData,onMouseEnter:a.onMouseEnter,onMouseLeave:a.onMouseLeave,onRightClick:a.onRightClick,prefixCls:a.prefixCls,showLine:a.showLine,showIcon:a.showIcon,draggable:a.draggable,dragOver:i.dragOverNodeKey===o&&0===this.dropPosition,dragOverGapTop:i.dragOverNodeKey===o&&this.dropPosition===-1,dragOverGapBottom:i.dragOverNodeKey===o&&1===this.dropPosition,_dropTrigger:this._dropTrigger,expanded:i.expandedKeys.indexOf(o)!==-1,selected:i.selectedKeys.indexOf(o)!==-1,openTransitionName:this.getOpenTransitionName(),openAnimation:a.openAnimation,filterTreeNode:this.filterTreeNode.bind(this)};return a.checkable&&(l.checkable=a.checkable,a.checkStrictly?(i.checkedKeys&&(l.checked=i.checkedKeys.indexOf(o)!==-1||!1),a.checkedKeys.halfChecked?l.halfChecked=a.checkedKeys.halfChecked.indexOf(o)!==-1||!1:l.halfChecked=!1):(this.checkedKeys&&(l.checked=this.checkedKeys.indexOf(o)!==-1||!1),l.halfChecked=this.halfCheckedKeys.indexOf(o)!==-1),this.treeNodesStates[r]&&(0,h["default"])(l,this.treeNodesStates[r].siblingPosition)),f["default"].cloneElement(e,l)},t.prototype.render=function(){var e=this,t=this.props,n={className:(0,v["default"])(t.className,t.prefixCls),role:"tree-node"};return t.focusable&&(n.tabIndex="0",n.onKeyDown=this.onKeyDown),t.checkable&&(this.checkedKeysChange||t.loadData)&&(t.checkStrictly?(this.treeNodesStates={},(0,m.loopAllChildren)(t.children,function(t,n,r,o,i){e.treeNodesStates[r]={siblingPosition:i}})):t._treeNodesStates?(this.treeNodesStates=t._treeNodesStates.treeNodesStates,this.halfCheckedKeys=t._treeNodesStates.halfCheckedKeys,this.checkedKeys=t._treeNodesStates.checkedKeys):!function(){var n=e.state.checkedKeys,r=void 0;!t.loadData&&e.checkKeys&&e._checkedKeys&&(0,m.arraysEqual)(e._checkedKeys,n)?r=e.checkKeys:!function(){var o=[];e.treeNodesStates={},(0,m.loopAllChildren)(t.children,function(t,r,i,a,s){e.treeNodesStates[i]={node:t,key:a,checked:!1,halfChecked:!1,siblingPosition:s},n.indexOf(a)!==-1&&(e.treeNodesStates[i].checked=!0,o.push(i))}),(0,m.handleCheckState)(e.treeNodesStates,(0,m.filterParentPosition)(o),!0),r=(0,m.getCheck)(e.treeNodesStates)}(),e.halfCheckedKeys=r.halfCheckedKeys,e.checkedKeys=r.checkedKeys}()),f["default"].createElement("ul",c({},n,{unselectable:!0,ref:"tree"}),f["default"].Children.map(t.children,this.renderTreeNode,this))},t}(f["default"].Component);g.propTypes={prefixCls:p.PropTypes.string,children:p.PropTypes.any,showLine:p.PropTypes.bool,showIcon:p.PropTypes.bool,selectable:p.PropTypes.bool,multiple:p.PropTypes.bool,checkable:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.node]),_treeNodesStates:p.PropTypes.object,checkStrictly:p.PropTypes.bool,draggable:p.PropTypes.bool,autoExpandParent:p.PropTypes.bool,defaultExpandAll:p.PropTypes.bool,defaultExpandedKeys:p.PropTypes.arrayOf(p.PropTypes.string),expandedKeys:p.PropTypes.arrayOf(p.PropTypes.string),defaultCheckedKeys:p.PropTypes.arrayOf(p.PropTypes.string),checkedKeys:p.PropTypes.oneOfType([p.PropTypes.arrayOf(p.PropTypes.string),p.PropTypes.object]),defaultSelectedKeys:p.PropTypes.arrayOf(p.PropTypes.string),selectedKeys:p.PropTypes.arrayOf(p.PropTypes.string),onExpand:p.PropTypes.func,onCheck:p.PropTypes.func,onSelect:p.PropTypes.func,loadData:p.PropTypes.func,onMouseEnter:p.PropTypes.func,onMouseLeave:p.PropTypes.func,onRightClick:p.PropTypes.func,onDragStart:p.PropTypes.func,onDragEnter:p.PropTypes.func,onDragOver:p.PropTypes.func,onDragLeave:p.PropTypes.func,onDrop:p.PropTypes.func,filterTreeNode:p.PropTypes.func,openTransitionName:p.PropTypes.string,openAnimation:p.PropTypes.oneOfType([p.PropTypes.string,p.PropTypes.object])},g.defaultProps={prefixCls:"rc-tree",showLine:!1,showIcon:!0,selectable:!0,multiple:!1,checkable:!1,checkStrictly:!1,draggable:!1,autoExpandParent:!0,defaultExpandAll:!1,defaultExpandedKeys:[],defaultCheckedKeys:[],defaultSelectedKeys:[],onExpand:u,onCheck:u,onSelect:u,onDragStart:u,onDragEnter:u,onDragOver:u,onDragLeave:u,onDrop:u},t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},p=n(1),f=r(p),d=n(10),h=r(d),y=n(2),v=r(y),m=n(9),g=r(m),b=n(167),P="undefined"!=typeof window?(0,b.browser)(window.navigator):"",C=/.*(IE|Edge).+/.test(P),T="---",O=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));return["onExpand","onCheck","onContextMenu","onMouseEnter","onMouseLeave","onDragStart","onDragEnter","onDragOver","onDragLeave","onDrop"].forEach(function(e){r[e]=r[e].bind(r)}),r.state={dataLoading:!1,dragNodeHighlight:!1},r}return l(t,e),t.prototype.componentDidMount=function(){this.props.root._treeNodeInstances||(this.props.root._treeNodeInstances=[]),this.props.root._treeNodeInstances.push(this)},t.prototype.onCheck=function(){this.props.root.onCheck(this)},t.prototype.onSelect=function(){this.props.root.onSelect(this)},t.prototype.onMouseEnter=function(e){e.preventDefault(),this.props.root.onMouseEnter(e,this)},t.prototype.onMouseLeave=function(e){e.preventDefault(),this.props.root.onMouseLeave(e,this)},t.prototype.onContextMenu=function(e){e.preventDefault(),this.props.root.onContextMenu(e,this)},t.prototype.onDragStart=function(e){e.stopPropagation(),this.setState({dragNodeHighlight:!0}),this.props.root.onDragStart(e,this);try{e.dataTransfer.setData("text/plain","firefox-need-it")}finally{}},t.prototype.onDragEnter=function(e){e.preventDefault(),e.stopPropagation(),this.props.root.onDragEnter(e,this)},t.prototype.onDragOver=function(e){return e.preventDefault(),e.stopPropagation(),this.props.root.onDragOver(e,this),!1},t.prototype.onDragLeave=function(e){e.stopPropagation(),this.props.root.onDragLeave(e,this)},t.prototype.onDrop=function(e){e.preventDefault(),e.stopPropagation(),this.setState({dragNodeHighlight:!1}),this.props.root.onDrop(e,this)},t.prototype.onExpand=function(){var e=this,t=this.props.root.onExpand(this);t&&"object"===("undefined"==typeof t?"undefined":c(t))&&!function(){var n=function(t){e.setState({dataLoading:t})};n(!0),t.then(function(){n(!1)},function(){n(!1)})}()},t.prototype.onKeyDown=function(e){e.preventDefault()},t.prototype.renderSwitcher=function(e,t){var n=e.prefixCls,r=i({},n+"-switcher",!0);return e.showLine?"0-0"===e.pos?r[n+"-roots_"+t]=!0:(r[n+"-center_"+t]=!e.last,r[n+"-bottom_"+t]=e.last):r[n+"-noline_"+t]=!0,e.disabled?(r[n+"-switcher-disabled"]=!0,f["default"].createElement("span",{className:(0,v["default"])(r)})):f["default"].createElement("span",{className:(0,v["default"])(r),onClick:this.onExpand})},t.prototype.renderCheckbox=function(e){var t=e.prefixCls,n=i({},t+"-checkbox",!0);e.checked?n[t+"-checkbox-checked"]=!0:e.halfChecked&&(n[t+"-checkbox-indeterminate"]=!0);var r=null;return"boolean"!=typeof e.checkable&&(r=e.checkable),e.disabled||e.disableCheckbox?(n[t+"-checkbox-disabled"]=!0,f["default"].createElement("span",{ref:"checkbox",className:(0,v["default"])(n)},r)):f["default"].createElement("span",{ref:"checkbox",className:(0,v["default"])(n),onClick:this.onCheck},r)},t.prototype.renderChildren=function(e){var n=this.renderFirst;this.renderFirst=1;var r=!0;!n&&e.expanded&&(r=!1);var o=e.children,a=o;if(o&&(o.type===t||Array.isArray(o)&&o.every(function(e){return e.type===t}))){var s,l=(s={},i(s,e.prefixCls+"-child-tree",!0),i(s,e.prefixCls+"-child-tree-open",e.expanded),s);e.showLine&&(l[e.prefixCls+"-line"]=!e.last);var p={};e.openTransitionName?p.transitionName=e.openTransitionName:"object"===c(e.openAnimation)&&(p.animation=(0,h["default"])({},e.openAnimation),r||delete p.animation.appear),a=f["default"].createElement(g["default"],u({},p,{showProp:"data-expanded",transitionAppear:r,component:""}),e.expanded?f["default"].createElement("ul",{className:(0,v["default"])(l),"data-expanded":e.expanded},f["default"].Children.map(o,function(t,n){return e.root.renderTreeNode(t,n,e.pos)},e.root)):null)}return a},t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.expanded?"open":"close",a=(e={},i(e,r+"-iconEle",!0),i(e,r+"-icon_loading",this.state.dataLoading),i(e,r+"-icon__"+o,!0),e),s=!0,l=n.title,c=this.renderChildren(n);c&&c!==n.children||(c=null,n.loadData&&!n.isLeaf||(s=!1));var p=function(){var e=n.showIcon||n.loadData&&t.state.dataLoading?f["default"].createElement("span",{className:(0,v["default"])(a)}):null,o=f["default"].createElement("span",{className:r+"-title"},l),i={};return n.disabled||((n.selected||!n._dropTrigger&&t.state.dragNodeHighlight)&&(i.className=r+"-node-selected"),i.onClick=function(e){e.preventDefault(),n.selectable&&t.onSelect()},n.onRightClick&&(i.onContextMenu=t.onContextMenu),n.onMouseEnter&&(i.onMouseEnter=t.onMouseEnter),n.onMouseLeave&&(i.onMouseLeave=t.onMouseLeave),n.draggable&&(C&&(i.href="#"),i.draggable=!0,i["aria-grabbed"]=!0,i.onDragStart=t.onDragStart)),f["default"].createElement("a",u({ref:"selectHandle",title:"string"==typeof l?l:""},i),e,o)},d={};n.draggable&&(d.onDragEnter=this.onDragEnter,d.onDragOver=this.onDragOver,d.onDragLeave=this.onDragLeave,d.onDrop=this.onDrop);var h="",y="";n.disabled?h=r+"-treenode-disabled":n.dragOver?y="drag-over":n.dragOverGapTop?y="drag-over-gap-top":n.dragOverGapBottom&&(y="drag-over-gap-bottom");var m=n.filterTreeNode(this)?"filter-node":"",g=function(){var e,t=(e={},i(e,r+"-switcher",!0),i(e,r+"-switcher-noop",!0),e);return n.showLine?(t[r+"-center_docu"]=!n.last,t[r+"-bottom_docu"]=n.last):t[r+"-noline_docu"]=!0,f["default"].createElement("span",{className:(0,v["default"])(t)})};return f["default"].createElement("li",u({},d,{ref:"li",className:(0,v["default"])(n.className,h,y,m)}),s?this.renderSwitcher(n,o):g(),n.checkable?this.renderCheckbox(n):null,p(),c)},t}(f["default"].Component);O.isTreeNode=1,O.propTypes={prefixCls:p.PropTypes.string,disabled:p.PropTypes.bool,disableCheckbox:p.PropTypes.bool,expanded:p.PropTypes.bool,isLeaf:p.PropTypes.bool,root:p.PropTypes.object,onSelect:p.PropTypes.func},O.defaultProps={title:T},t["default"]=O,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(7),i=r(o),a=n(1),s=r(a),l=n(4),u=r(l),c=n(385),p=r(c),f=n(9),d=r(f),h=n(491),y=r(h),v=n(168),m=r(v),g=s["default"].createClass({displayName:"Popup",propTypes:{visible:a.PropTypes.bool,style:a.PropTypes.object,getClassNameFromAlign:a.PropTypes.func,onAlign:a.PropTypes.func,getRootDomNode:a.PropTypes.func,onMouseEnter:a.PropTypes.func,align:a.PropTypes.any,destroyPopupOnHide:a.PropTypes.bool,className:a.PropTypes.string,prefixCls:a.PropTypes.string,onMouseLeave:a.PropTypes.func},componentDidMount:function(){this.rootNode=this.getPopupDomNode()},onAlign:function(e,t){var n=this.props,r=n.getClassNameFromAlign(n.align),o=n.getClassNameFromAlign(t);r!==o&&(this.currentAlignClassName=o,e.className=this.getClassName(o)),n.onAlign(e,t)},getPopupDomNode:function(){return u["default"].findDOMNode(this.refs.popup)},getTarget:function(){return this.props.getRootDomNode()},getMaskTransitionName:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},getClassName:function(e){return this.props.prefixCls+" "+this.props.className+" "+e},getPopupElement:function(){var e=this.props,t=e.align,n=e.style,r=e.visible,o=e.prefixCls,a=e.destroyPopupOnHide,l=this.getClassName(this.currentAlignClassName||e.getClassNameFromAlign(t)),u=o+"-hidden";r||(this.currentAlignClassName=null);var c=(0,i["default"])({},n,this.getZIndexStyle()),f={className:l,prefixCls:o,ref:"popup",onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:c};return a?s["default"].createElement(d["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName()},r?s["default"].createElement(p["default"],{target:this.getTarget,key:"popup",ref:this.saveAlign,monitorWindowResize:!0,align:t,onAlign:this.onAlign},s["default"].createElement(y["default"],(0,i["default"])({visible:!0},f),e.children)):null):s["default"].createElement(d["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName(),showProp:"xVisible"},s["default"].createElement(p["default"],{target:this.getTarget,key:"popup",ref:this.saveAlign,monitorWindowResize:!0,xVisible:r,childrenProps:{visible:"xVisible"},disabled:!r,align:t,onAlign:this.onAlign},s["default"].createElement(y["default"],(0,i["default"])({hiddenClassName:u},f),e.children)))},getZIndexStyle:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getMaskElement:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=s["default"].createElement(m["default"],{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=s["default"].createElement(d["default"],{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},saveAlign:function(e){this.alignInstance=e},render:function(){return s["default"].createElement("div",null,this.getMaskElement(),this.getPopupElement())}});t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(168),s=r(a),l=i["default"].createClass({displayName:"PopupInner",propTypes:{hiddenClassName:o.PropTypes.string,className:o.PropTypes.string,prefixCls:o.PropTypes.string,onMouseEnter:o.PropTypes.func,onMouseLeave:o.PropTypes.func,children:o.PropTypes.any},render:function(){var e=this.props,t=e.className;return e.visible||(t+=" "+e.hiddenClassName),i["default"].createElement("div",{className:t,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:e.style},i["default"].createElement(s["default"],{className:e.prefixCls+"-content",visible:e.visible},e.children))}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(){return""}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),s=r(a),l=n(1),u=r(l),c=n(4),p=r(c),f=n(171),d=r(f),h=n(20),y=r(h),v=n(490),m=r(v),g=n(493),b=n(501),P=r(b),C=["onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur"],T=u["default"].createClass({displayName:"Trigger",propTypes:{children:l.PropTypes.any,action:l.PropTypes.oneOfType([l.PropTypes.string,l.PropTypes.arrayOf(l.PropTypes.string)]),showAction:l.PropTypes.any,hideAction:l.PropTypes.any,getPopupClassNameFromAlign:l.PropTypes.any,onPopupVisibleChange:l.PropTypes.func,afterPopupVisibleChange:l.PropTypes.func,popup:l.PropTypes.oneOfType([l.PropTypes.node,l.PropTypes.func]).isRequired,popupStyle:l.PropTypes.object,prefixCls:l.PropTypes.string,popupClassName:l.PropTypes.string,popupPlacement:l.PropTypes.string,builtinPlacements:l.PropTypes.object,popupTransitionName:l.PropTypes.string,popupAnimation:l.PropTypes.any,mouseEnterDelay:l.PropTypes.number,mouseLeaveDelay:l.PropTypes.number,zIndex:l.PropTypes.number,focusDelay:l.PropTypes.number,blurDelay:l.PropTypes.number,getPopupContainer:l.PropTypes.func,destroyPopupOnHide:l.PropTypes.bool,mask:l.PropTypes.bool,maskClosable:l.PropTypes.bool,onPopupAlign:l.PropTypes.func,popupAlign:l.PropTypes.object,popupVisible:l.PropTypes.bool,maskTransitionName:l.PropTypes.string,maskAnimation:l.PropTypes.string},mixins:[(0,P["default"])({autoMount:!1,isVisible:function(e){return e.state.popupVisible},getContainer:function(e){var t=document.createElement("div"),n=e.props.getPopupContainer?e.props.getPopupContainer((0,c.findDOMNode)(e)):document.body;return n.appendChild(t),t},getComponent:function(e){var t=e.props,n=e.state,r={};return e.isMouseEnterToShow()&&(r.onMouseEnter=e.onPopupMouseEnter),e.isMouseLeaveToHide()&&(r.onMouseLeave=e.onPopupMouseLeave),u["default"].createElement(m["default"],(0,s["default"])({prefixCls:t.prefixCls,destroyPopupOnHide:t.destroyPopupOnHide,visible:n.popupVisible,className:t.popupClassName,action:t.action,align:e.getPopupAlign(),onAlign:t.onPopupAlign,animation:t.popupAnimation,getClassNameFromAlign:e.getPopupClassNameFromAlign},r,{getRootDomNode:e.getRootDomNode,style:t.popupStyle,mask:t.mask,zIndex:t.zIndex,transitionName:t.popupTransitionName,maskAnimation:t.maskAnimation,maskTransitionName:t.maskTransitionName}),"function"==typeof t.popup?t.popup():t.popup)}})],getDefaultProps:function(){return{prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:i,onPopupVisibleChange:o,afterPopupVisibleChange:o,onPopupAlign:o,popupClassName:"",mouseEnterDelay:0,mouseLeaveDelay:.1,focusDelay:0,blurDelay:.15,popupStyle:{},destroyPopupOnHide:!1,popupAlign:{},defaultPopupVisible:!1,mask:!1,maskClosable:!0,action:[],showAction:[],hideAction:[]}},getInitialState:function(){var e=this.props,t=void 0;return t="popupVisible"in e?!!e.popupVisible:!!e.defaultPopupVisible,{popupVisible:t}},componentWillMount:function(){var e=this;C.forEach(function(t){e["fire"+t]=function(n){e.fireEvents(t,n)}})},componentDidMount:function(){this.componentDidUpdate({},{popupVisible:this.state.popupVisible})},componentWillReceiveProps:function(e){var t=e.popupVisible;void 0!==t&&this.setState({popupVisible:t})},componentDidUpdate:function(e,t){var n=this.props,r=this.state;return this.renderComponent(null,function(){t.popupVisible!==r.popupVisible&&n.afterPopupVisibleChange(r.popupVisible)}),this.isClickToHide()&&r.popupVisible?void(this.clickOutsideHandler||(this.clickOutsideHandler=(0,y["default"])(document,"mousedown",this.onDocumentClick),this.touchOutsideHandler=(0,y["default"])(document,"touchstart",this.onDocumentClick))):void(this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.touchOutsideHandler.remove(),this.clickOutsideHandler=null,this.touchOutsideHandler=null))},componentWillUnmount:function(){this.clearDelayTimer(),this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.touchOutsideHandler.remove(),this.clickOutsideHandler=null,this.touchOutsideHandler=null)},onMouseEnter:function(e){this.fireEvents("onMouseEnter",e),this.delaySetPopupVisible(!0,this.props.mouseEnterDelay)},onMouseLeave:function(e){this.fireEvents("onMouseLeave",e),this.delaySetPopupVisible(!1,this.props.mouseLeaveDelay)},onPopupMouseEnter:function(){this.clearDelayTimer()},onPopupMouseLeave:function(e){e.relatedTarget&&!e.relatedTarget.setTimeout&&this._component&&(0,d["default"])(this._component.getPopupDomNode(),e.relatedTarget)||this.delaySetPopupVisible(!1,this.props.mouseLeaveDelay)},onFocus:function(e){this.fireEvents("onFocus",e),this.clearDelayTimer(),this.isFocusToShow()&&(this.focusTime=Date.now(),this.delaySetPopupVisible(!0,this.props.focusDelay))},onMouseDown:function(e){this.fireEvents("onMouseDown",e),this.preClickTime=Date.now()},onTouchStart:function(e){this.fireEvents("onTouchStart",e),this.preTouchTime=Date.now()},onBlur:function(e){this.fireEvents("onBlur",e),this.clearDelayTimer(),this.isBlurToHide()&&this.delaySetPopupVisible(!1,this.props.blurDelay)},onClick:function(e){if(this.fireEvents("onClick",e),this.focusTime){var t=void 0;if(this.preClickTime&&this.preTouchTime?t=Math.min(this.preClickTime,this.preTouchTime):this.preClickTime?t=this.preClickTime:this.preTouchTime&&(t=this.preTouchTime),Math.abs(t-this.focusTime)<20)return;this.focusTime=0}this.preClickTime=0,this.preTouchTime=0,e.preventDefault();var n=!this.state.popupVisible;(this.isClickToHide()&&!n||n&&this.isClickToShow())&&this.setPopupVisible(!this.state.popupVisible)},onDocumentClick:function(e){if(!this.props.mask||this.props.maskClosable){var t=e.target,n=(0,c.findDOMNode)(this),r=this.getPopupDomNode();(0,d["default"])(n,t)||(0,d["default"])(r,t)||this.close()}},getPopupDomNode:function(){return this._component&&this._component.isMounted()?this._component.getPopupDomNode():null},getRootDomNode:function(){return p["default"].findDOMNode(this)},getPopupClassNameFromAlign:function(e){var t=[],n=this.props,r=n.popupPlacement,o=n.builtinPlacements,i=n.prefixCls;return r&&o&&t.push((0,g.getPopupClassNameFromAlign)(o,i,e)),n.getPopupClassNameFromAlign&&t.push(n.getPopupClassNameFromAlign(e)),t.join(" ")},getPopupAlign:function(){var e=this.props,t=e.popupPlacement,n=e.popupAlign,r=e.builtinPlacements;return t&&r?(0,g.getAlignFromPlacement)(r,t,n):n},setPopupVisible:function(e){this.clearDelayTimer(),this.state.popupVisible!==e&&("popupVisible"in this.props||this.setState({popupVisible:e}),this.props.onPopupVisibleChange(e))},delaySetPopupVisible:function(e,t){var n=this,r=1e3*t;this.clearDelayTimer(),r?this.delayTimer=setTimeout(function(){n.setPopupVisible(e),n.clearDelayTimer()},r):this.setPopupVisible(e)},clearDelayTimer:function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},createTwoChains:function(e){var t=this.props.children.props,n=this.props;return t[e]&&n[e]?this["fire"+e]:t[e]||n[e]},isClickToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("click")!==-1||n.indexOf("click")!==-1},isClickToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("click")!==-1||n.indexOf("click")!==-1},isMouseEnterToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("hover")!==-1||n.indexOf("mouseEnter")!==-1},isMouseLeaveToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("hover")!==-1||n.indexOf("mouseLeave")!==-1},isFocusToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("focus")!==-1||n.indexOf("focus")!==-1},isBlurToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("focus")!==-1||n.indexOf("blur")!==-1},forcePopupAlign:function(){this.state.popupVisible&&this.popupInstance&&this.popupInstance.alignInstance&&this.popupInstance.alignInstance.forceAlign()},fireEvents:function(e,t){var n=this.props.children.props[e];n&&n(t);var r=this.props[e];r&&r(t)},close:function(){this.setPopupVisible(!1)},render:function(){var e=this.props,t=e.children,n=u["default"].Children.only(t),r={};return this.isClickToHide()||this.isClickToShow()?(r.onClick=this.onClick,r.onMouseDown=this.onMouseDown,r.onTouchStart=this.onTouchStart):(r.onClick=this.createTwoChains("onClick"),r.onMouseDown=this.createTwoChains("onMouseDown"),r.onTouchStart=this.createTwoChains("onTouchStart")),this.isMouseEnterToShow()?r.onMouseEnter=this.onMouseEnter:r.onMouseEnter=this.createTwoChains("onMouseEnter"),this.isMouseLeaveToHide()?r.onMouseLeave=this.onMouseLeave:r.onMouseLeave=this.createTwoChains("onMouseLeave"),this.isFocusToShow()||this.isBlurToHide()?(r.onFocus=this.onFocus,r.onBlur=this.onBlur):(r.onFocus=this.createTwoChains("onFocus"),r.onBlur=this.createTwoChains("onBlur")),u["default"].cloneElement(n,r)}});t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return e[0]===t[0]&&e[1]===t[1]}function i(e,t,n){var r=e[t]||{};return(0,l["default"])({},r,n)}function a(e,t,n){var r=n.points;for(var i in e)if(e.hasOwnProperty(i)&&o(e[i].points,r))return t+"-placement-"+i;return""}Object.defineProperty(t,"__esModule",{value:!0});var s=n(7),l=r(s);t.getAlignFromPlacement=i,t.getPopupClassNameFromAlign=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(7),i=r(o),a=n(498),s=r(a),l=n(1),u=r(l),c=n(169),p=r(c),f=u["default"].createClass({displayName:"AjaxUploader",propTypes:{component:l.PropTypes.string,style:l.PropTypes.object,prefixCls:l.PropTypes.string,multiple:l.PropTypes.bool,disabled:l.PropTypes.bool,accept:l.PropTypes.string,children:l.PropTypes.any,onStart:l.PropTypes.func,data:l.PropTypes.oneOfType([l.PropTypes.object,l.PropTypes.func]),headers:l.PropTypes.object,beforeUpload:l.PropTypes.func,withCredentials:l.PropTypes.bool},getInitialState:function(){return this.reqs={},{uid:(0,p["default"])()}},componentWillUnmount:function(){this.abort()},onChange:function(e){var t=e.target.files;this.uploadFiles(t),this.reset()},onClick:function(){var e=this.refs.file;e&&e.click()},onKeyDown:function(e){"Enter"===e.key&&this.onClick()},onFileDrop:function(e){if("dragover"===e.type)return void e.preventDefault();var t=e.dataTransfer.files;this.uploadFiles(t),e.preventDefault()},uploadFiles:function(e){for(var t=Array.prototype.slice.call(e),n=t.length,r=0;r<n;r++){var o=t[r];o.uid=(0,p["default"])(),this.upload(o)}},upload:function(e){var t=this,n=this.props;if(!n.beforeUpload)return setTimeout(function(){return t.post(e)},0);var r=n.beforeUpload(e);r&&r.then?r.then(function(n){"[object File]"===Object.prototype.toString.call(n)?t.post(n):t.post(e)}):r!==!1&&setTimeout(function(){return t.post(e)},0)},post:function(e){var t=this;if(this.isMounted()){var n=this.props,r=n.data,o=n.onStart;"function"==typeof r&&(r=r(e));var i=e.uid;this.reqs[i]=(0,s["default"])({action:n.action,filename:n.name,file:e,data:r,headers:n.headers,withCredentials:n.withCredentials,onProgress:function(t){n.onProgress(t,e)},onSuccess:function(r){delete t.reqs[i],n.onSuccess(r,e)},onError:function(r,o){delete t.reqs[i],n.onError(r,o,e)}}),o(e)}},reset:function(){this.setState({uid:(0,p["default"])()})},abort:function(e){var t=this.reqs;if(e){var n=e;e&&e.uid&&(n=e.uid),t[n]&&(t[n].abort(),delete t[n])}else Object.keys(t).forEach(function(e){t[e].abort(),delete t[e]})},render:function(){var e=this.props,t=e.component,n=e.prefixCls,r=e.disabled,o=e.style,a=e.multiple,s=e.accept,l=e.children,c=r?{className:n+" "+n+"-disabled"}:{className:""+n,onClick:this.onClick,onKeyDown:this.onKeyDown,onDrop:this.onFileDrop,onDragOver:this.onFileDrop,tabIndex:"0"};return u["default"].createElement(t,(0,i["default"])({},c,{role:"button",style:o}),u["default"].createElement("input",{type:"file",ref:"file",key:this.state.uid,style:{display:"none"},accept:s,multiple:a,onChange:this.onChange}),l)}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(7),i=r(o),a=n(1),s=r(a),l=n(4),u=r(l),c=n(169),p=r(c),f=n(499),d=r(f),h={position:"absolute",top:0,opacity:0,filter:"alpha(opacity=0)",left:0,zIndex:9999},y=s["default"].createClass({displayName:"IframeUploader",propTypes:{component:a.PropTypes.string,style:a.PropTypes.object,disabled:a.PropTypes.bool,prefixCls:a.PropTypes.string,accept:a.PropTypes.string,onStart:a.PropTypes.func,multiple:a.PropTypes.bool,children:a.PropTypes.any,data:a.PropTypes.oneOfType([a.PropTypes.object,a.PropTypes.func]),action:a.PropTypes.string,name:a.PropTypes.string},getInitialState:function(){return this.file={},{uploading:!1}},componentDidMount:function(){this.updateIframeWH(),this.initIframe()},componentDidUpdate:function(){this.updateIframeWH()},onLoad:function(){if(this.state.uploading){var e=this.props,t=this.file,n=void 0;try{var r=this.getIframeDocument(),o=r.getElementsByTagName("script")[0];o&&o.parentNode===r.body&&r.body.removeChild(o),n=r.body.innerHTML,e.onSuccess(n,t)}catch(i){(0,d["default"])(!1,"cross domain error for Upload. Maybe server should return document.domain script. see Note from https://github.com/react-component/upload"),n="cross-domain",e.onError(i,null,t)}this.endUpload()}},onChange:function(){var e=this,t=this.getFormInputNode(),n=this.file={uid:(0,p["default"])(),name:t.value};this.startUpload();var r=this.props;if(!r.beforeUpload)return this.post(n);var o=r.beforeUpload(n);o&&o.then?o.then(function(){e.post(n)},function(){e.endUpload()}):o!==!1?this.post(n):this.endUpload()},getIframeNode:function(){return this.refs.iframe},getIframeDocument:function(){return this.getIframeNode().contentDocument},getFormNode:function(){return this.getIframeDocument().getElementById("form")},getFormInputNode:function(){return this.getIframeDocument().getElementById("input")},getFormDataNode:function(){return this.getIframeDocument().getElementById("data")},getFileForMultiple:function(e){return this.props.multiple?[e]:e},getIframeHTML:function(e){var t="",n="";return e&&(t='<script>document.domain="'+e+'";</script>',n='<input name="_documentDomain" value="'+e+'" />'),'\n <!DOCTYPE html>\n <html>\n <head>\n <meta http-equiv="X-UA-Compatible" content="IE=edge" />\n <style>\n body,html {padding:0;margin:0;border:0;overflow:hidden;}\n </style>\n '+t+'\n </head>\n <body>\n <form method="post"\n encType="multipart/form-data"\n action="'+this.props.action+'" id="form"\n style="display:block;height:9999px;position:relative;overflow:hidden;">\n <input id="input" type="file"\n name="'+this.props.name+'"\n style="position:absolute;top:0;right:0;height:9999px;font-size:9999px;cursor:pointer;"/>\n '+n+'\n <span id="data"></span>\n </form>\n </body>\n </html>\n '; },initIframeSrc:function(){this.domain&&(this.getIframeNode().src="javascript:void((function(){\n var d = document;\n d.open();\n d.domain='"+this.domain+"';\n d.write('');\n d.close();\n })())")},initIframe:function(){var e=this.getIframeNode(),t=e.contentWindow,n=void 0;this.domain=this.domain||"",this.initIframeSrc();try{n=t.document}catch(r){this.domain=document.domain,this.initIframeSrc(),t=e.contentWindow,n=t.document}n.open("text/html","replace"),n.write(this.getIframeHTML(this.domain)),n.close(),this.getFormInputNode().onchange=this.onChange},endUpload:function(){this.state.uploading&&(this.file={},this.state.uploading=!1,this.setState({uploading:!1}),this.initIframe())},startUpload:function(){this.state.uploading||(this.state.uploading=!0,this.setState({uploading:!0}))},updateIframeWH:function(){var e=u["default"].findDOMNode(this),t=this.getIframeNode();t.style.height=e.offsetHeight+"px",t.style.width=e.offsetWidth+"px"},abort:function(e){if(e){var t=e;e&&e.uid&&(t=e.uid),t===this.file.uid&&this.endUpload()}else this.endUpload()},post:function(e){var t=this.getFormNode(),n=this.getFormDataNode(),r=this.props.data,o=this.props.onStart;"function"==typeof r&&(r=r(e));var i=[];for(var a in r)r.hasOwnProperty(a)&&i.push('<input name="'+a+'" value="'+r[a]+'"/>');n.innerHTML=i.join(""),t.submit(),n.innerHTML="",o(e)},render:function(){var e=this.props,t=e.component,n=e.disabled,r=e.prefixCls,o=e.children,a=e.style,l=(0,i["default"])({},h,{display:this.state.uploading||n?"none":""});return s["default"].createElement(t,{className:n?r+" "+r+"-disabled":""+r,style:(0,i["default"])({position:"relative",zIndex:0},a)},s["default"].createElement("iframe",{ref:"iframe",onLoad:this.onLoad,style:l}),o)}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var i=n(7),a=r(i),s=n(1),l=r(s),u=n(494),c=r(u),p=n(495),f=r(p),d=l["default"].createClass({displayName:"Upload",propTypes:{component:s.PropTypes.string,style:s.PropTypes.object,prefixCls:s.PropTypes.string,action:s.PropTypes.string,name:s.PropTypes.string,multipart:s.PropTypes.bool,onError:s.PropTypes.func,onSuccess:s.PropTypes.func,onProgress:s.PropTypes.func,onStart:s.PropTypes.func,data:s.PropTypes.oneOfType([s.PropTypes.object,s.PropTypes.func]),headers:s.PropTypes.object,accept:s.PropTypes.string,multiple:s.PropTypes.bool,disabled:s.PropTypes.bool,beforeUpload:s.PropTypes.func,onReady:s.PropTypes.func,withCredentials:s.PropTypes.bool,supportServerRender:s.PropTypes.bool},getDefaultProps:function(){return{component:"span",prefixCls:"rc-upload",data:{},headers:{},name:"file",multipart:!1,onProgress:o,onReady:o,onStart:o,onError:o,onSuccess:o,supportServerRender:!1,multiple:!1,beforeUpload:null,withCredentials:!1}},getInitialState:function(){return{Component:null}},componentDidMount:function(){this.props.supportServerRender&&this.setState({Component:this.getComponent()},this.props.onReady)},getComponent:function(){return"undefined"!=typeof FormData?c["default"]:f["default"]},abort:function(e){this.refs.inner.abort(e)},render:function(){if(this.props.supportServerRender){var e=this.state.Component;return e?l["default"].createElement(e,(0,a["default"])({},this.props,{ref:"inner"})):null}var t=this.getComponent();return l["default"].createElement(t,(0,a["default"])({},this.props,{ref:"inner"}))}});t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(496)},function(e,t){"use strict";function n(e,t){var n="cannot post "+e.action+" "+t.status+"'",r=new Error(n);return r.status=t.status,r.method="post",r.url=e.action,r}function r(e){var t=e.responseText||e.response;if(!t)return t;try{return JSON.parse(t)}catch(n){return t}}function o(e){var t=new XMLHttpRequest;t.upload&&(t.upload.onprogress=function(t){t.total>0&&(t.percent=t.loaded/t.total*100),e.onProgress(t)});var o=new FormData;e.data&&Object.keys(e.data).map(function(t){o.append(t,e.data[t])}),o.append(e.filename,e.file),t.onerror=function(t){e.onError(t)},t.onload=function(){return t.status<200||t.status>=300?e.onError(n(e,t),r(t)):void e.onSuccess(r(t))},t.open("post",e.action,!0),e.withCredentials&&"withCredentials"in t&&(t.withCredentials=!0);var i=e.headers||{};null!==i["X-Requested-With"]&&t.setRequestHeader("X-Requested-With","XMLHttpRequest");for(var a in i)i.hasOwnProperty(a)&&null!==i[a]&&t.setRequestHeader(a,i[a]);return t.send(o),{abort:function(){t.abort()}}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o,e.exports=t["default"]},22,function(e,t,n){"use strict";var r=n(1);e.exports=function(e){var t=[];return r.Children.forEach(e,function(e){t.push(e)}),t}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=document.createElement("div");return document.body.appendChild(e),e}function i(e){function t(e,t,n){(!c||e._component||c(e))&&(e._container||(e._container=d(e)),l["default"].unstable_renderSubtreeIntoContainer(e,p(e,t),e._container,function(){e._component=this,n&&n.call(this)}))}function n(e){if(e._container){var t=e._container;l["default"].unmountComponentAtNode(t),t.parentNode.removeChild(t),e._container=null}}var r=e.autoMount,i=void 0===r||r,s=e.autoDestroy,u=void 0===s||s,c=e.isVisible,p=e.getComponent,f=e.getContainer,d=void 0===f?o:f,h=void 0;return i&&(h=a({},h,{componentDidMount:function(){t(this)},componentDidUpdate:function(){t(this)}})),i&&u||(h=a({},h,{renderComponent:function(e,n){t(this,e,n)}})),h=u?a({},h,{componentWillUnmount:function(){n(this)}}):a({},h,{removeContainer:function(){n(this)}})}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=i;var s=n(4),l=r(s);e.exports=t["default"]},function(e,t){"use strict";var n=0;e.exports=function(){return Date.now()+"_"+n++}},function(e,t,n){var r=n(315),o=r&&n(370),i=n(135),a={media:function(e,t){e=i(e),"function"==typeof t&&(t={match:t}),r&&o.register(e,t),this._responsiveMediaHandlers||(this._responsiveMediaHandlers=[]),this._responsiveMediaHandlers.push({query:e,handler:t})},componentWillUnmount:function(){this._responsiveMediaHandlers&&this._responsiveMediaHandlers.forEach(function(e){r&&o.unregister(e.query,e.handler)})}};e.exports=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.NextArrow=t.PrevArrow=void 0;var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(2),l=r(s);t.PrevArrow=a["default"].createClass({displayName:"PrevArrow",clickHandler:function(e,t){t&&t.preventDefault(),this.props.clickHandler(e,t)},render:function(){var e={"slick-arrow":!0,"slick-prev":!0},t=this.clickHandler.bind(this,{message:"previous"});!this.props.infinite&&(0===this.props.currentSlide||this.props.slideCount<=this.props.slidesToShow)&&(e["slick-disabled"]=!0,t=null);var n,r={key:"0","data-role":"none",className:(0,l["default"])(e),style:{display:"block"},onClick:t};return n=this.props.prevArrow?a["default"].cloneElement(this.props.prevArrow,r):a["default"].createElement("button",o({key:"0",type:"button"},r)," Previous")}}),t.NextArrow=a["default"].createClass({displayName:"NextArrow",clickHandler:function(e,t){t&&t.preventDefault(),this.props.clickHandler(e,t)},render:function(){var e={"slick-arrow":!0,"slick-next":!0},t=this.clickHandler.bind(this,{message:"next"});this.props.infinite||(this.props.centerMode&&this.props.currentSlide>=this.props.slideCount-1?(e["slick-disabled"]=!0,t=null):this.props.currentSlide>=this.props.slideCount-this.props.slidesToShow&&(e["slick-disabled"]=!0,t=null),this.props.slideCount<=this.props.slidesToShow&&(e["slick-disabled"]=!0,t=null));var n,r={key:"1","data-role":"none",className:(0,l["default"])(e),style:{display:"block"},onClick:t};return n=this.props.nextArrow?a["default"].cloneElement(this.props.nextArrow,r):a["default"].createElement("button",o({key:"1",type:"button"},r)," Next")}})},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.Dots=void 0;var o=n(1),i=r(o),a=n(2),s=r(a),l=function(e){var t;return t=Math.ceil(e.slideCount/e.slidesToScroll)};t.Dots=i["default"].createClass({displayName:"Dots",clickHandler:function(e,t){t.preventDefault(),this.props.clickHandler(e)},render:function(){var e=this,t=l({slideCount:this.props.slideCount,slidesToScroll:this.props.slidesToScroll}),n=Array.apply(null,Array(t+1).join("0").split("")).map(function(t,n){var r=n*e.props.slidesToScroll,o=n*e.props.slidesToScroll+(e.props.slidesToScroll-1),a=(0,s["default"])({"slick-active":e.props.currentSlide>=r&&e.props.currentSlide<=o}),l={message:"dots",index:n,slidesToScroll:e.props.slidesToScroll,currentSlide:e.props.currentSlide};return i["default"].createElement("li",{key:n,className:a},i["default"].createElement("button",{onClick:e.clickHandler.bind(e,l)},n+1))});return i["default"].createElement("ul",{className:this.props.dotsClass,style:{display:"block"}},n)}})},function(e,t,n){"use strict";e.exports=n(510)},function(e,t){"use strict";var n={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,slideCount:null,slideWidth:null,swipeLeft:null,touchObject:{startX:0,startY:0,curX:0,curY:0},lazyLoadedList:[],initialized:!1,edgeDragged:!1,swiped:!1,trackStyle:{},trackWidth:0};e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.InnerSlider=void 0;var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(509),l=r(s),u=n(173),c=r(u),p=n(507),f=r(p),d=n(172),h=r(d),y=n(2),v=r(y),m=n(511),g=n(505),b=n(504);t.InnerSlider=a["default"].createClass({displayName:"InnerSlider",mixins:[c["default"],l["default"]],list:null,track:null,listRefHandler:function(e){this.list=e},trackRefHandler:function(e){this.track=e},getInitialState:function(){return o({},f["default"],{currentSlide:this.props.initialSlide})},getDefaultProps:function(){return h["default"]},componentWillMount:function(){this.props.init&&this.props.init(),this.setState({mounted:!0});for(var e=[],t=0;t<a["default"].Children.count(this.props.children);t++)t>=this.state.currentSlide&&t<this.state.currentSlide+this.props.slidesToShow&&e.push(t);this.props.lazyLoad&&0===this.state.lazyLoadedList.length&&this.setState({lazyLoadedList:e})},componentDidMount:function(){this.initialize(this.props),this.adaptHeight(),window.addEventListener?window.addEventListener("resize",this.onWindowResized):window.attachEvent("onresize",this.onWindowResized)},componentWillUnmount:function(){this.animationEndCallback&&clearTimeout(this.animationEndCallback),window.addEventListener?window.removeEventListener("resize",this.onWindowResized):window.detachEvent("onresize",this.onWindowResized),this.state.autoPlayTimer&&window.clearInterval(this.state.autoPlayTimer)},componentWillReceiveProps:function(e){this.props.slickGoTo!=e.slickGoTo?this.changeSlide({message:"index",index:e.slickGoTo,currentSlide:this.state.currentSlide}):this.state.currentSlide>=e.children.length?(this.update(e),this.changeSlide({message:"index",index:e.children.length-e.slidesToShow,currentSlide:this.state.currentSlide})):this.update(e)},componentDidUpdate:function(){this.adaptHeight()},onWindowResized:function(){this.update(this.props),this.setState({animating:!1})},slickPrev:function(){this.changeSlide({message:"previous"})},slickNext:function(){this.changeSlide({message:"next"})},slickGoTo:function(e){"number"==typeof e&&this.changeSlide({message:"index",index:e,currentSlide:this.state.currentSlide})},render:function(){var e,t=(0,v["default"])("slick-initialized","slick-slider",this.props.className),n={fade:this.props.fade,cssEase:this.props.cssEase,speed:this.props.speed,infinite:this.props.infinite,centerMode:this.props.centerMode,focusOnSelect:this.props.focusOnSelect?this.selectHandler:new Function,currentSlide:this.state.currentSlide,lazyLoad:this.props.lazyLoad,lazyLoadedList:this.state.lazyLoadedList,rtl:this.props.rtl,slideWidth:this.state.slideWidth,slidesToShow:this.props.slidesToShow,slidesToScroll:this.props.slidesToScroll,slideCount:this.state.slideCount,trackStyle:this.state.trackStyle,variableWidth:this.props.variableWidth};if(this.props.dots===!0&&this.state.slideCount>=this.props.slidesToShow){var r={dotsClass:this.props.dotsClass,slideCount:this.state.slideCount,slidesToShow:this.props.slidesToShow,currentSlide:this.state.currentSlide,slidesToScroll:this.props.slidesToScroll,clickHandler:this.changeSlide};e=a["default"].createElement(g.Dots,r)}var i,s,l={infinite:this.props.infinite,centerMode:this.props.centerMode,currentSlide:this.state.currentSlide,slideCount:this.state.slideCount,slidesToShow:this.props.slidesToShow,prevArrow:this.props.prevArrow,nextArrow:this.props.nextArrow,clickHandler:this.changeSlide};this.props.arrows&&(i=a["default"].createElement(b.PrevArrow,l),s=a["default"].createElement(b.NextArrow,l));var u=null;return this.props.vertical===!1?this.props.centerMode===!0&&(u={padding:"0px "+this.props.centerPadding}):this.props.centerMode===!0&&(u={padding:this.props.centerPadding+" 0px"}),a["default"].createElement("div",{className:t,onMouseEnter:this.onInnerSliderEnter,onMouseLeave:this.onInnerSliderLeave},i,a["default"].createElement("div",{ref:this.listRefHandler,className:"slick-list",style:u,onMouseDown:this.swipeStart,onMouseMove:this.state.dragging?this.swipeMove:null,onMouseUp:this.swipeEnd,onMouseLeave:this.state.dragging?this.swipeEnd:null,onTouchStart:this.swipeStart,onTouchMove:this.state.dragging?this.swipeMove:null,onTouchEnd:this.swipeEnd,onTouchCancel:this.state.dragging?this.swipeEnd:null,onKeyDown:this.props.accessibility?this.keyHandler:null},a["default"].createElement(m.Track,o({ref:this.trackRefHandler},n),this.props.children)),s,e)}})},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(174),i=n(173),a=(r(i),n(10)),s=r(a),l={changeSlide:function(e){var t,n,r,o,i,a=this.props,s=a.slidesToScroll,l=a.slidesToShow,u=this.state,c=u.slideCount,p=u.currentSlide;if(o=c%s!==0,t=o?0:(c-p)%s,"previous"===e.message)r=0===t?s:l-t,i=p-r,this.props.lazyLoad&&(n=p-r,i=n===-1?c-1:n);else if("next"===e.message)r=0===t?s:t,i=p+r,this.props.lazyLoad&&(i=(p+s)%c+t);else if("dots"===e.message||"children"===e.message){if(i=e.index*e.slidesToScroll,i===e.currentSlide)return}else if("index"===e.message&&(i=parseInt(e.index),i===e.currentSlide))return;this.slideHandler(i)},keyHandler:function(e){e.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===e.keyCode&&this.props.accessibility===!0?this.changeSlide({message:this.props.rtl===!0?"next":"previous"}):39===e.keyCode&&this.props.accessibility===!0&&this.changeSlide({message:this.props.rtl===!0?"previous":"next"}))},selectHandler:function(e){this.changeSlide(e)},swipeStart:function(e){var t,n;this.props.swipe===!1||"ontouchend"in document&&this.props.swipe===!1||this.props.draggable===!1&&e.type.indexOf("mouse")!==-1||(t=void 0!==e.touches?e.touches[0].pageX:e.clientX,n=void 0!==e.touches?e.touches[0].pageY:e.clientY,this.setState({dragging:!0,touchObject:{startX:t,startY:n,curX:t,curY:n}}))},swipeMove:function(e){if(!this.state.dragging)return void e.preventDefault();if(!this.state.animating){var t,n,r,i=this.state.touchObject;n=(0,o.getTrackLeft)((0,s["default"])({slideIndex:this.state.currentSlide,trackRef:this.track},this.props,this.state)),i.curX=e.touches?e.touches[0].pageX:e.clientX,i.curY=e.touches?e.touches[0].pageY:e.clientY,i.swipeLength=Math.round(Math.sqrt(Math.pow(i.curX-i.startX,2))),r=(this.props.rtl===!1?1:-1)*(i.curX>i.startX?1:-1);var a=this.state.currentSlide,l=Math.ceil(this.state.slideCount/this.props.slidesToScroll),u=this.swipeDirection(this.state.touchObject),c=i.swipeLength;this.props.infinite===!1&&(0===a&&"right"===u||a+1>=l&&"left"===u)&&(c=i.swipeLength*this.props.edgeFriction,this.state.edgeDragged===!1&&this.props.edgeEvent&&(this.props.edgeEvent(u),this.setState({edgeDragged:!0}))),this.state.swiped===!1&&this.props.swipeEvent&&(this.props.swipeEvent(u),this.setState({swiped:!0})),t=n+c*r,this.setState({touchObject:i,swipeLeft:t,trackStyle:(0,o.getTrackCSS)((0,s["default"])({left:t},this.props,this.state))}),Math.abs(i.curX-i.startX)<.8*Math.abs(i.curY-i.startY)||i.swipeLength>4&&e.preventDefault()}},swipeEnd:function(e){if(!this.state.dragging)return void e.preventDefault();var t=this.state.touchObject,n=this.state.listWidth/this.props.touchThreshold,r=this.swipeDirection(t);if(this.setState({dragging:!1,edgeDragged:!1,swiped:!1,swipeLeft:null,touchObject:{}}),t.swipeLength)if(t.swipeLength>n)e.preventDefault(),"left"===r?this.slideHandler(this.state.currentSlide+this.props.slidesToScroll):"right"===r?this.slideHandler(this.state.currentSlide-this.props.slidesToScroll):this.slideHandler(this.state.currentSlide);else{var i=(0,o.getTrackLeft)((0,s["default"])({slideIndex:this.state.currentSlide,trackRef:this.track},this.props,this.state));this.setState({trackStyle:(0,o.getTrackAnimateCSS)((0,s["default"])({left:i},this.props,this.state))})}},onInnerSliderEnter:function(e){this.props.autoplay&&this.props.pauseOnHover&&this.pause()},onInnerSliderLeave:function(e){this.props.autoplay&&this.props.pauseOnHover&&this.autoPlay()}};t["default"]=l},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(508),l=n(10),u=r(l),c=n(135),p=r(c),f=n(503),d=r(f),h=n(172),y=r(h),v=a["default"].createClass({displayName:"Slider",mixins:[d["default"]],innerSlider:null,innerSliderRefHandler:function(e){this.innerSlider=e},getInitialState:function(){return{breakpoint:null}},componentWillMount:function(){var e=this;if(this.props.responsive){var t=this.props.responsive.map(function(e){return e.breakpoint});t.sort(function(e,t){return e-t}),t.forEach(function(n,r){var o;o=0===r?(0,p["default"])({minWidth:0,maxWidth:n}):(0,p["default"])({minWidth:t[r-1],maxWidth:n}),e.media(o,function(){e.setState({breakpoint:n})})});var n=(0,p["default"])({minWidth:t.slice(-1)[0]});this.media(n,function(){e.setState({breakpoint:null})})}},slickPrev:function(){this.innerSlider.slickPrev()},slickNext:function(){this.innerSlider.slickNext()},slickGoTo:function(e){this.innerSlider.slickGoTo(e)},render:function(){var e,t,n=this;this.state.breakpoint?(t=this.props.responsive.filter(function(e){return e.breakpoint===n.state.breakpoint}),e="unslick"===t[0].settings?"unslick":(0,u["default"])({},this.props,t[0].settings)):e=(0,u["default"])({},y["default"],this.props);var r=this.props.children;return Array.isArray(r)||(r=[r]),r=r.filter(function(e){return!!e}),"unslick"===e?a["default"].createElement("div",null,r):a["default"].createElement(s.InnerSlider,o({ref:this.innerSliderRefHandler},e),r)}});e.exports=v},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.Track=void 0;var o=n(1),i=r(o),a=n(10),s=r(a),l=n(2),u=r(l),c=function(e){var t,n,r,o,i;return i=e.rtl?e.slideCount-1-e.index:e.index,r=i<0||i>=e.slideCount,e.centerMode?(o=Math.floor(e.slidesToShow/2),n=(i-e.currentSlide)%e.slideCount===0,i>e.currentSlide-o-1&&i<=e.currentSlide+o&&(t=!0)):t=e.currentSlide<=i&&i<e.currentSlide+e.slidesToShow,(0,u["default"])({"slick-slide":!0,"slick-active":t,"slick-center":n,"slick-cloned":r})},p=function(e){var t={};return void 0!==e.variableWidth&&e.variableWidth!==!1||(t.width=e.slideWidth),e.fade&&(t.position="relative",t.left=-e.index*e.slideWidth,t.opacity=e.currentSlide===e.index?1:0,t.transition="opacity "+e.speed+"ms "+e.cssEase,t.WebkitTransition="opacity "+e.speed+"ms "+e.cssEase),t},f=function(e,t){return null===e.key||void 0===e.key?t:e.key},d=function(e){var t,n=[],r=[],o=[],a=i["default"].Children.count(e.children);return i["default"].Children.forEach(e.children,function(l,d){var h=void 0,y={message:"children",index:d,slidesToScroll:e.slidesToScroll,currentSlide:e.currentSlide};h=!e.lazyLoad|(e.lazyLoad&&e.lazyLoadedList.indexOf(d)>=0)?l:i["default"].createElement("div",null);var v,m=p((0,s["default"])({},e,{index:d})),g=c((0,s["default"])({index:d},e));v=h.props.className?(0,u["default"])(g,h.props.className):g;var b=function(t){h.props&&h.props.onClick&&h.props.onClick(t),e.focusOnSelect(y)};if(n.push(i["default"].cloneElement(h,{key:"original"+f(h,d),"data-index":d,className:v,tabIndex:"-1",style:(0,s["default"])({outline:"none"},h.props.style||{},m),onClick:b})),e.infinite&&e.fade===!1){var P=e.variableWidth?e.slidesToShow+1:e.slidesToShow;d>=a-P&&(t=-(a-d),r.push(i["default"].cloneElement(h,{key:"precloned"+f(h,t),"data-index":t,className:v,style:(0,s["default"])({},h.props.style||{},m),onClick:b}))),d<P&&(t=a+d,o.push(i["default"].cloneElement(h,{key:"postcloned"+f(h,t),"data-index":t,className:v,style:(0,s["default"])({},h.props.style||{},m),onClick:b})))}}),e.rtl?r.concat(n,o).reverse():r.concat(n,o)};t.Track=i["default"].createClass({displayName:"Track",render:function(){var e=d.call(this,this.props);return i["default"].createElement("div",{className:"slick-track",style:this.props.trackStyle},e)}})},function(e,t,n){"use strict";var r=n(513),o={shouldComponentUpdate:function(e,t){return r(this,e,t)}};e.exports=o},function(e,t,n){"use strict";function r(e,t,n){return!o(e.props,t)||!o(e.state,n)}var o=n(371);e.exports=r},function(e,t){var n=function(e){return e.replace(/[A-Z]/g,function(e){return"-"+e.toLowerCase()}).toLowerCase()};e.exports=n},function(e,t,n){var r,o;!function(e){function t(e){var t=e.length,r=n.type(e);return"function"!==r&&!n.isWindow(e)&&(!(1!==e.nodeType||!t)||("array"===r||0===t||"number"==typeof t&&t>0&&t-1 in e))}if(!e.jQuery){var n=function(e,t){return new n.fn.init(e,t)};n.isWindow=function(e){return null!=e&&e==e.window},n.type=function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?o[a.call(e)]||"object":typeof e},n.isArray=Array.isArray||function(e){return"array"===n.type(e)},n.isPlainObject=function(e){var t;if(!e||"object"!==n.type(e)||e.nodeType||n.isWindow(e))return!1;try{if(e.constructor&&!i.call(e,"constructor")&&!i.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}for(t in e);return void 0===t||i.call(e,t)},n.each=function(e,n,r){var o,i=0,a=e.length,s=t(e);if(r){if(s)for(;i<a&&(o=n.apply(e[i],r),o!==!1);i++);else for(i in e)if(o=n.apply(e[i],r),o===!1)break}else if(s)for(;i<a&&(o=n.call(e[i],i,e[i]),o!==!1);i++);else for(i in e)if(o=n.call(e[i],i,e[i]),o===!1)break;return e},n.data=function(e,t,o){if(void 0===o){var i=e[n.expando],a=i&&r[i];if(void 0===t)return a;if(a&&t in a)return a[t]}else if(void 0!==t){var i=e[n.expando]||(e[n.expando]=++n.uuid);return r[i]=r[i]||{},r[i][t]=o,o}},n.removeData=function(e,t){var o=e[n.expando],i=o&&r[o];i&&n.each(t,function(e,t){delete i[t]})},n.extend=function(){var e,t,r,o,i,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[l]||{},l++),"object"!=typeof s&&"function"!==n.type(s)&&(s={}),l===u&&(s=this,l--);l<u;l++)if(null!=(i=arguments[l]))for(o in i)e=s[o],r=i[o],s!==r&&(c&&r&&(n.isPlainObject(r)||(t=n.isArray(r)))?(t?(t=!1,a=e&&n.isArray(e)?e:[]):a=e&&n.isPlainObject(e)?e:{},s[o]=n.extend(c,a,r)):void 0!==r&&(s[o]=r));return s},n.queue=function(e,r,o){function i(e,n){var r=n||[];return null!=e&&(t(Object(e))?!function(e,t){for(var n=+t.length,r=0,o=e.length;r<n;)e[o++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[o++]=t[r++];return e.length=o,e}(r,"string"==typeof e?[e]:e):[].push.call(r,e)),r}if(e){r=(r||"fx")+"queue";var a=n.data(e,r);return o?(!a||n.isArray(o)?a=n.data(e,r,i(o)):a.push(o),a):a||[]}},n.dequeue=function(e,t){n.each(e.nodeType?[e]:e,function(e,r){t=t||"fx";var o=n.queue(r,t),i=o.shift();"inprogress"===i&&(i=o.shift()),i&&("fx"===t&&o.unshift("inprogress"),i.call(r,function(){n.dequeue(r,t)}))})},n.fn=n.prototype={init:function(e){if(e.nodeType)return this[0]=e,this;throw new Error("Not a DOM node.")},offset:function(){var t=this[0].getBoundingClientRect?this[0].getBoundingClientRect():{top:0,left:0};return{top:t.top+(e.pageYOffset||document.scrollTop||0)-(document.clientTop||0),left:t.left+(e.pageXOffset||document.scrollLeft||0)-(document.clientLeft||0)}},position:function(){function e(){for(var e=this.offsetParent||document;e&&"html"===!e.nodeType.toLowerCase&&"static"===e.style.position;)e=e.offsetParent;return e||document}var t=this[0],e=e.apply(t),r=this.offset(),o=/^(?:body|html)$/i.test(e.nodeName)?{top:0,left:0}:n(e).offset();return r.top-=parseFloat(t.style.marginTop)||0,r.left-=parseFloat(t.style.marginLeft)||0,e.style&&(o.top+=parseFloat(e.style.borderTopWidth)||0,o.left+=parseFloat(e.style.borderLeftWidth)||0),{top:r.top-o.top,left:r.left-o.left}}};var r={};n.expando="velocity"+(new Date).getTime(),n.uuid=0;for(var o={},i=o.hasOwnProperty,a=o.toString,s="Boolean Number String Function Array Date RegExp Object Error".split(" "),l=0;l<s.length;l++)o["[object "+s[l]+"]"]=s[l].toLowerCase();n.fn.init.prototype=n.fn,e.Velocity={Utilities:n}}}(window),function(i){"object"==typeof e&&"object"==typeof e.exports?e.exports=i():(r=i,o="function"==typeof r?r.call(t,n,t,e):r,!(void 0!==o&&(e.exports=o)))}(function(){return function(e,t,n,r){function o(e){for(var t=-1,n=e?e.length:0,r=[];++t<n;){var o=e[t];o&&r.push(o)}return r}function i(e){return y.isWrapped(e)?e=[].slice.call(e):y.isNode(e)&&(e=[e]),e}function a(e){var t=f.data(e,"velocity");return null===t?r:t}function s(e){return function(t){return Math.round(t*e)*(1/e)}}function l(e,n,r,o){function i(e,t){return 1-3*t+3*e}function a(e,t){return 3*t-6*e}function s(e){return 3*e}function l(e,t,n){return((i(t,n)*e+a(t,n))*e+s(t))*e}function u(e,t,n){return 3*i(t,n)*e*e+2*a(t,n)*e+s(t)}function c(t,n){for(var o=0;o<y;++o){var i=u(n,e,r);if(0===i)return n;var a=l(n,e,r)-t;n-=a/i}return n}function p(){for(var t=0;t<b;++t)O[t]=l(t*P,e,r)}function f(t,n,o){var i,a,s=0;do a=n+(o-n)/2,i=l(a,e,r)-t,i>0?o=a:n=a;while(Math.abs(i)>m&&++s<g);return a}function d(t){for(var n=0,o=1,i=b-1;o!=i&&O[o]<=t;++o)n+=P;--o;var a=(t-O[o])/(O[o+1]-O[o]),s=n+a*P,l=u(s,e,r);return l>=v?c(t,s):0==l?s:f(t,n,n+P)}function h(){w=!0,e==n&&r==o||p()}var y=4,v=.001,m=1e-7,g=10,b=11,P=1/(b-1),C="Float32Array"in t;if(4!==arguments.length)return!1;for(var T=0;T<4;++T)if("number"!=typeof arguments[T]||isNaN(arguments[T])||!isFinite(arguments[T]))return!1;e=Math.min(e,1),r=Math.min(r,1),e=Math.max(e,0),r=Math.max(r,0);var O=C?new Float32Array(b):new Array(b),w=!1,x=function(t){return w||h(),e===n&&r===o?t:0===t?0:1===t?1:l(d(t),n,o)};x.getControlPoints=function(){return[{x:e,y:n},{x:r,y:o}]};var E="generateBezier("+[e,n,r,o]+")";return x.toString=function(){return E},x}function u(e,t){var n=e;return y.isString(e)?b.Easings[e]||(n=!1):n=y.isArray(e)&&1===e.length?s.apply(null,e):y.isArray(e)&&2===e.length?P.apply(null,e.concat([t])):!(!y.isArray(e)||4!==e.length)&&l.apply(null,e),n===!1&&(n=b.Easings[b.defaults.easing]?b.defaults.easing:g),n}function c(e){if(e){var t=(new Date).getTime(),n=b.State.calls.length;n>1e4&&(b.State.calls=o(b.State.calls));for(var i=0;i<n;i++)if(b.State.calls[i]){var s=b.State.calls[i],l=s[0],u=s[2],d=s[3],h=!!d,v=null;d||(d=b.State.calls[i][3]=t-16);for(var m=Math.min((t-d)/u.duration,1),g=0,P=l.length;g<P;g++){var T=l[g],w=T.element;if(a(w)){var x=!1;if(u.display!==r&&null!==u.display&&"none"!==u.display){if("flex"===u.display){var E=["-webkit-box","-moz-box","-ms-flexbox","-webkit-flex"];f.each(E,function(e,t){C.setPropertyValue(w,"display",t)})}C.setPropertyValue(w,"display",u.display)}u.visibility!==r&&"hidden"!==u.visibility&&C.setPropertyValue(w,"visibility",u.visibility);for(var S in T)if("element"!==S){var k,N=T[S],j=y.isString(N.easing)?b.Easings[N.easing]:N.easing;if(1===m)k=N.endValue;else{var _=N.endValue-N.startValue;if(k=N.startValue+_*j(m,u,_),!h&&k===N.currentValue)continue}if(N.currentValue=k,"tween"===S)v=k;else{if(C.Hooks.registered[S]){var M=C.Hooks.getRoot(S),D=a(w).rootPropertyValueCache[M];D&&(N.rootPropertyValue=D)}var A=C.setPropertyValue(w,S,N.currentValue+(0===parseFloat(k)?"":N.unitType),N.rootPropertyValue,N.scrollData);C.Hooks.registered[S]&&(C.Normalizations.registered[M]?a(w).rootPropertyValueCache[M]=C.Normalizations.registered[M]("extract",null,A[1]):a(w).rootPropertyValueCache[M]=A[1]),"transform"===A[0]&&(x=!0)}}u.mobileHA&&a(w).transformCache.translate3d===r&&(a(w).transformCache.translate3d="(0px, 0px, 0px)",x=!0),x&&C.flushTransformCache(w)}}u.display!==r&&"none"!==u.display&&(b.State.calls[i][2].display=!1),u.visibility!==r&&"hidden"!==u.visibility&&(b.State.calls[i][2].visibility=!1),u.progress&&u.progress.call(s[1],s[1],m,Math.max(0,d+u.duration-t),d,v),1===m&&p(i)}}b.State.isTicking&&O(c)}function p(e,t){if(!b.State.calls[e])return!1;for(var n=b.State.calls[e][0],o=b.State.calls[e][1],i=b.State.calls[e][2],s=b.State.calls[e][4],l=!1,u=0,c=n.length;u<c;u++){var p=n[u].element;if(t||i.loop||("none"===i.display&&C.setPropertyValue(p,"display",i.display),"hidden"===i.visibility&&C.setPropertyValue(p,"visibility",i.visibility)),i.loop!==!0&&(f.queue(p)[1]===r||!/\.velocityQueueEntryFlag/i.test(f.queue(p)[1]))&&a(p)){a(p).isAnimating=!1,a(p).rootPropertyValueCache={};var d=!1;f.each(C.Lists.transforms3D,function(e,t){var n=/^scale/.test(t)?1:0,o=a(p).transformCache[t];a(p).transformCache[t]!==r&&new RegExp("^\\("+n+"[^.]").test(o)&&(d=!0,delete a(p).transformCache[t])}),i.mobileHA&&(d=!0,delete a(p).transformCache.translate3d),d&&C.flushTransformCache(p),C.Values.removeClass(p,"velocity-animating")}if(!t&&i.complete&&!i.loop&&u===c-1)try{i.complete.call(o,o)}catch(h){setTimeout(function(){throw h},1)}s&&i.loop!==!0&&s(o),a(p)&&i.loop===!0&&!t&&(f.each(a(p).tweensContainer,function(e,t){/^rotate/.test(e)&&360===parseFloat(t.endValue)&&(t.endValue=0,t.startValue=360),/^backgroundPosition/.test(e)&&100===parseFloat(t.endValue)&&"%"===t.unitType&&(t.endValue=0,t.startValue=100)}),b(p,"reverse",{loop:!0,delay:i.delay})),i.queue!==!1&&f.dequeue(p,i.queue)}b.State.calls[e]=!1;for(var y=0,v=b.State.calls.length;y<v;y++)if(b.State.calls[y]!==!1){l=!0;break}l===!1&&(b.State.isTicking=!1,delete b.State.calls,b.State.calls=[])}var f,d=function(){if(n.documentMode)return n.documentMode;for(var e=7;e>4;e--){var t=n.createElement("div");if(t.innerHTML="<!--[if IE "+e+"]><span></span><![endif]-->",t.getElementsByTagName("span").length)return t=null,e}return r}(),h=function(){var e=0;return t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||function(t){var n,r=(new Date).getTime();return n=Math.max(0,16-(r-e)),e=r+n,setTimeout(function(){t(r+n)},n)}}(),y={isString:function(e){return"string"==typeof e},isArray:Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},isFunction:function(e){return"[object Function]"===Object.prototype.toString.call(e)},isNode:function(e){return e&&e.nodeType},isNodeList:function(e){return"object"==typeof e&&/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(e))&&e.length!==r&&(0===e.length||"object"==typeof e[0]&&e[0].nodeType>0)},isWrapped:function(e){return e&&(e.jquery||t.Zepto&&t.Zepto.zepto.isZ(e))},isSVG:function(e){return t.SVGElement&&e instanceof t.SVGElement},isEmptyObject:function(e){for(var t in e)return!1;return!0}},v=!1;if(e.fn&&e.fn.jquery?(f=e,v=!0):f=t.Velocity.Utilities,d<=8&&!v)throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity.");if(d<=7)return void(jQuery.fn.velocity=jQuery.fn.animate); var m=400,g="swing",b={State:{isMobile:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),isAndroid:/Android/i.test(navigator.userAgent),isGingerbread:/Android 2\.3\.[3-7]/i.test(navigator.userAgent),isChrome:t.chrome,isFirefox:/Firefox/i.test(navigator.userAgent),prefixElement:n.createElement("div"),prefixMatches:{},scrollAnchor:null,scrollPropertyLeft:null,scrollPropertyTop:null,isTicking:!1,calls:[]},CSS:{},Utilities:f,Redirects:{},Easings:{},Promise:t.Promise,defaults:{queue:"",duration:m,easing:g,begin:r,complete:r,progress:r,display:r,visibility:r,loop:!1,delay:!1,mobileHA:!0,_cacheValues:!0},init:function(e){f.data(e,"velocity",{isSVG:y.isSVG(e),isAnimating:!1,computedStyle:null,tweensContainer:null,rootPropertyValueCache:{},transformCache:{}})},hook:null,mock:!1,version:{major:1,minor:2,patch:2},debug:!1};t.pageYOffset!==r?(b.State.scrollAnchor=t,b.State.scrollPropertyLeft="pageXOffset",b.State.scrollPropertyTop="pageYOffset"):(b.State.scrollAnchor=n.documentElement||n.body.parentNode||n.body,b.State.scrollPropertyLeft="scrollLeft",b.State.scrollPropertyTop="scrollTop");var P=function(){function e(e){return-e.tension*e.x-e.friction*e.v}function t(t,n,r){var o={x:t.x+r.dx*n,v:t.v+r.dv*n,tension:t.tension,friction:t.friction};return{dx:o.v,dv:e(o)}}function n(n,r){var o={dx:n.v,dv:e(n)},i=t(n,.5*r,o),a=t(n,.5*r,i),s=t(n,r,a),l=1/6*(o.dx+2*(i.dx+a.dx)+s.dx),u=1/6*(o.dv+2*(i.dv+a.dv)+s.dv);return n.x=n.x+l*r,n.v=n.v+u*r,n}return function r(e,t,o){var i,a,s,l={x:-1,v:0,tension:null,friction:null},u=[0],c=0,p=1e-4,f=.016;for(e=parseFloat(e)||500,t=parseFloat(t)||20,o=o||null,l.tension=e,l.friction=t,i=null!==o,i?(c=r(e,t),a=c/o*f):a=f;;)if(s=n(s||l,a),u.push(1+s.x),c+=16,!(Math.abs(s.x)>p&&Math.abs(s.v)>p))break;return i?function(e){return u[e*(u.length-1)|0]}:c}}();b.Easings={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},spring:function(e){return 1-Math.cos(4.5*e*Math.PI)*Math.exp(6*-e)}},f.each([["ease",[.25,.1,.25,1]],["ease-in",[.42,0,1,1]],["ease-out",[0,0,.58,1]],["ease-in-out",[.42,0,.58,1]],["easeInSine",[.47,0,.745,.715]],["easeOutSine",[.39,.575,.565,1]],["easeInOutSine",[.445,.05,.55,.95]],["easeInQuad",[.55,.085,.68,.53]],["easeOutQuad",[.25,.46,.45,.94]],["easeInOutQuad",[.455,.03,.515,.955]],["easeInCubic",[.55,.055,.675,.19]],["easeOutCubic",[.215,.61,.355,1]],["easeInOutCubic",[.645,.045,.355,1]],["easeInQuart",[.895,.03,.685,.22]],["easeOutQuart",[.165,.84,.44,1]],["easeInOutQuart",[.77,0,.175,1]],["easeInQuint",[.755,.05,.855,.06]],["easeOutQuint",[.23,1,.32,1]],["easeInOutQuint",[.86,0,.07,1]],["easeInExpo",[.95,.05,.795,.035]],["easeOutExpo",[.19,1,.22,1]],["easeInOutExpo",[1,0,0,1]],["easeInCirc",[.6,.04,.98,.335]],["easeOutCirc",[.075,.82,.165,1]],["easeInOutCirc",[.785,.135,.15,.86]]],function(e,t){b.Easings[t[0]]=l.apply(null,t[1])});var C=b.CSS={RegEx:{isHex:/^#([A-f\d]{3}){1,2}$/i,valueUnwrap:/^[A-z]+\((.*)\)$/i,wrappedValueAlreadyExtracted:/[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,valueSplit:/([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/gi},Lists:{colors:["fill","stroke","stopColor","color","backgroundColor","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor","outlineColor"],transformsBase:["translateX","translateY","scale","scaleX","scaleY","skewX","skewY","rotateZ"],transforms3D:["transformPerspective","translateZ","scaleZ","rotateX","rotateY"]},Hooks:{templates:{textShadow:["Color X Y Blur","black 0px 0px 0px"],boxShadow:["Color X Y Blur Spread","black 0px 0px 0px 0px"],clip:["Top Right Bottom Left","0px 0px 0px 0px"],backgroundPosition:["X Y","0% 0%"],transformOrigin:["X Y Z","50% 50% 0px"],perspectiveOrigin:["X Y","50% 50%"]},registered:{},register:function(){for(var e=0;e<C.Lists.colors.length;e++){var t="color"===C.Lists.colors[e]?"0 0 0 1":"255 255 255 1";C.Hooks.templates[C.Lists.colors[e]]=["Red Green Blue Alpha",t]}var n,r,o;if(d)for(n in C.Hooks.templates){r=C.Hooks.templates[n],o=r[0].split(" ");var i=r[1].match(C.RegEx.valueSplit);"Color"===o[0]&&(o.push(o.shift()),i.push(i.shift()),C.Hooks.templates[n]=[o.join(" "),i.join(" ")])}for(n in C.Hooks.templates){r=C.Hooks.templates[n],o=r[0].split(" ");for(var e in o){var a=n+o[e],s=e;C.Hooks.registered[a]=[n,s]}}},getRoot:function(e){var t=C.Hooks.registered[e];return t?t[0]:e},cleanRootPropertyValue:function(e,t){return C.RegEx.valueUnwrap.test(t)&&(t=t.match(C.RegEx.valueUnwrap)[1]),C.Values.isCSSNullValue(t)&&(t=C.Hooks.templates[e][1]),t},extractValue:function(e,t){var n=C.Hooks.registered[e];if(n){var r=n[0],o=n[1];return t=C.Hooks.cleanRootPropertyValue(r,t),t.toString().match(C.RegEx.valueSplit)[o]}return t},injectValue:function(e,t,n){var r=C.Hooks.registered[e];if(r){var o,i,a=r[0],s=r[1];return n=C.Hooks.cleanRootPropertyValue(a,n),o=n.toString().match(C.RegEx.valueSplit),o[s]=t,i=o.join(" ")}return n}},Normalizations:{registered:{clip:function(e,t,n){switch(e){case"name":return"clip";case"extract":var r;return C.RegEx.wrappedValueAlreadyExtracted.test(n)?r=n:(r=n.toString().match(C.RegEx.valueUnwrap),r=r?r[1].replace(/,(\s+)?/g," "):n),r;case"inject":return"rect("+n+")"}},blur:function(e,t,n){switch(e){case"name":return b.State.isFirefox?"filter":"-webkit-filter";case"extract":var r=parseFloat(n);if(!r&&0!==r){var o=n.toString().match(/blur\(([0-9]+[A-z]+)\)/i);r=o?o[1]:0}return r;case"inject":return parseFloat(n)?"blur("+n+")":"none"}},opacity:function(e,t,n){if(d<=8)switch(e){case"name":return"filter";case"extract":var r=n.toString().match(/alpha\(opacity=(.*)\)/i);return n=r?r[1]/100:1;case"inject":return t.style.zoom=1,parseFloat(n)>=1?"":"alpha(opacity="+parseInt(100*parseFloat(n),10)+")"}else switch(e){case"name":return"opacity";case"extract":return n;case"inject":return n}}},register:function(){d<=9||b.State.isGingerbread||(C.Lists.transformsBase=C.Lists.transformsBase.concat(C.Lists.transforms3D));for(var e=0;e<C.Lists.transformsBase.length;e++)!function(){var t=C.Lists.transformsBase[e];C.Normalizations.registered[t]=function(e,n,o){switch(e){case"name":return"transform";case"extract":return a(n)===r||a(n).transformCache[t]===r?/^scale/i.test(t)?1:0:a(n).transformCache[t].replace(/[()]/g,"");case"inject":var i=!1;switch(t.substr(0,t.length-1)){case"translate":i=!/(%|px|em|rem|vw|vh|\d)$/i.test(o);break;case"scal":case"scale":b.State.isAndroid&&a(n).transformCache[t]===r&&o<1&&(o=1),i=!/(\d)$/i.test(o);break;case"skew":i=!/(deg|\d)$/i.test(o);break;case"rotate":i=!/(deg|\d)$/i.test(o)}return i||(a(n).transformCache[t]="("+o+")"),a(n).transformCache[t]}}}();for(var e=0;e<C.Lists.colors.length;e++)!function(){var t=C.Lists.colors[e];C.Normalizations.registered[t]=function(e,n,o){switch(e){case"name":return t;case"extract":var i;if(C.RegEx.wrappedValueAlreadyExtracted.test(o))i=o;else{var a,s={black:"rgb(0, 0, 0)",blue:"rgb(0, 0, 255)",gray:"rgb(128, 128, 128)",green:"rgb(0, 128, 0)",red:"rgb(255, 0, 0)",white:"rgb(255, 255, 255)"};/^[A-z]+$/i.test(o)?a=s[o]!==r?s[o]:s.black:C.RegEx.isHex.test(o)?a="rgb("+C.Values.hexToRgb(o).join(" ")+")":/^rgba?\(/i.test(o)||(a=s.black),i=(a||o).toString().match(C.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g," ")}return d<=8||3!==i.split(" ").length||(i+=" 1"),i;case"inject":return d<=8?4===o.split(" ").length&&(o=o.split(/\s+/).slice(0,3).join(" ")):3===o.split(" ").length&&(o+=" 1"),(d<=8?"rgb":"rgba")+"("+o.replace(/\s+/g,",").replace(/\.(\d)+(?=,)/g,"")+")"}}}()}},Names:{camelCase:function(e){return e.replace(/-(\w)/g,function(e,t){return t.toUpperCase()})},SVGAttribute:function(e){var t="width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2";return(d||b.State.isAndroid&&!b.State.isChrome)&&(t+="|transform"),new RegExp("^("+t+")$","i").test(e)},prefixCheck:function(e){if(b.State.prefixMatches[e])return[b.State.prefixMatches[e],!0];for(var t=["","Webkit","Moz","ms","O"],n=0,r=t.length;n<r;n++){var o;if(o=0===n?e:t[n]+e.replace(/^\w/,function(e){return e.toUpperCase()}),y.isString(b.State.prefixElement.style[o]))return b.State.prefixMatches[e]=o,[o,!0]}return[e,!1]}},Values:{hexToRgb:function(e){var t,n=/^#?([a-f\d])([a-f\d])([a-f\d])$/i,r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;return e=e.replace(n,function(e,t,n,r){return t+t+n+n+r+r}),t=r.exec(e),t?[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]:[0,0,0]},isCSSNullValue:function(e){return 0==e||/^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(e)},getUnitType:function(e){return/^(rotate|skew)/i.test(e)?"deg":/(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(e)?"":"px"},getDisplayType:function(e){var t=e&&e.tagName.toString().toLowerCase();return/^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(t)?"inline":/^(li)$/i.test(t)?"list-item":/^(tr)$/i.test(t)?"table-row":/^(table)$/i.test(t)?"table":/^(tbody)$/i.test(t)?"table-row-group":"block"},addClass:function(e,t){e.classList?e.classList.add(t):e.className+=(e.className.length?" ":"")+t},removeClass:function(e,t){e.classList?e.classList.remove(t):e.className=e.className.toString().replace(new RegExp("(^|\\s)"+t.split(" ").join("|")+"(\\s|$)","gi")," ")}},getPropertyValue:function(e,n,o,i){function s(e,n){function o(){u&&C.setPropertyValue(e,"display","none")}var l=0;if(d<=8)l=f.css(e,n);else{var u=!1;if(/^(width|height)$/.test(n)&&0===C.getPropertyValue(e,"display")&&(u=!0,C.setPropertyValue(e,"display",C.Values.getDisplayType(e))),!i){if("height"===n&&"border-box"!==C.getPropertyValue(e,"boxSizing").toString().toLowerCase()){var c=e.offsetHeight-(parseFloat(C.getPropertyValue(e,"borderTopWidth"))||0)-(parseFloat(C.getPropertyValue(e,"borderBottomWidth"))||0)-(parseFloat(C.getPropertyValue(e,"paddingTop"))||0)-(parseFloat(C.getPropertyValue(e,"paddingBottom"))||0);return o(),c}if("width"===n&&"border-box"!==C.getPropertyValue(e,"boxSizing").toString().toLowerCase()){var p=e.offsetWidth-(parseFloat(C.getPropertyValue(e,"borderLeftWidth"))||0)-(parseFloat(C.getPropertyValue(e,"borderRightWidth"))||0)-(parseFloat(C.getPropertyValue(e,"paddingLeft"))||0)-(parseFloat(C.getPropertyValue(e,"paddingRight"))||0);return o(),p}}var h;h=a(e)===r?t.getComputedStyle(e,null):a(e).computedStyle?a(e).computedStyle:a(e).computedStyle=t.getComputedStyle(e,null),"borderColor"===n&&(n="borderTopColor"),l=9===d&&"filter"===n?h.getPropertyValue(n):h[n],""!==l&&null!==l||(l=e.style[n]),o()}if("auto"===l&&/^(top|right|bottom|left)$/i.test(n)){var y=s(e,"position");("fixed"===y||"absolute"===y&&/top|left/i.test(n))&&(l=f(e).position()[n]+"px")}return l}var l;if(C.Hooks.registered[n]){var u=n,c=C.Hooks.getRoot(u);o===r&&(o=C.getPropertyValue(e,C.Names.prefixCheck(c)[0])),C.Normalizations.registered[c]&&(o=C.Normalizations.registered[c]("extract",e,o)),l=C.Hooks.extractValue(u,o)}else if(C.Normalizations.registered[n]){var p,h;p=C.Normalizations.registered[n]("name",e),"transform"!==p&&(h=s(e,C.Names.prefixCheck(p)[0]),C.Values.isCSSNullValue(h)&&C.Hooks.templates[n]&&(h=C.Hooks.templates[n][1])),l=C.Normalizations.registered[n]("extract",e,h)}if(!/^[\d-]/.test(l))if(a(e)&&a(e).isSVG&&C.Names.SVGAttribute(n))if(/^(height|width)$/i.test(n))try{l=e.getBBox()[n]}catch(y){l=0}else l=e.getAttribute(n);else l=s(e,C.Names.prefixCheck(n)[0]);return C.Values.isCSSNullValue(l)&&(l=0),b.debug>=2&&console.log("Get "+n+": "+l),l},setPropertyValue:function(e,n,r,o,i){var s=n;if("scroll"===n)i.container?i.container["scroll"+i.direction]=r:"Left"===i.direction?t.scrollTo(r,i.alternateValue):t.scrollTo(i.alternateValue,r);else if(C.Normalizations.registered[n]&&"transform"===C.Normalizations.registered[n]("name",e))C.Normalizations.registered[n]("inject",e,r),s="transform",r=a(e).transformCache[n];else{if(C.Hooks.registered[n]){var l=n,u=C.Hooks.getRoot(n);o=o||C.getPropertyValue(e,u),r=C.Hooks.injectValue(l,r,o),n=u}if(C.Normalizations.registered[n]&&(r=C.Normalizations.registered[n]("inject",e,r),n=C.Normalizations.registered[n]("name",e)),s=C.Names.prefixCheck(n)[0],d<=8)try{e.style[s]=r}catch(c){b.debug&&console.log("Browser does not support ["+r+"] for ["+s+"]")}else a(e)&&a(e).isSVG&&C.Names.SVGAttribute(n)?e.setAttribute(n,r):e.style[s]=r;b.debug>=2&&console.log("Set "+n+" ("+s+"): "+r)}return[s,r]},flushTransformCache:function(e){function t(t){return parseFloat(C.getPropertyValue(e,t))}var n="";if((d||b.State.isAndroid&&!b.State.isChrome)&&a(e).isSVG){var r={translate:[t("translateX"),t("translateY")],skewX:[t("skewX")],skewY:[t("skewY")],scale:1!==t("scale")?[t("scale"),t("scale")]:[t("scaleX"),t("scaleY")],rotate:[t("rotateZ"),0,0]};f.each(a(e).transformCache,function(e){/^translate/i.test(e)?e="translate":/^scale/i.test(e)?e="scale":/^rotate/i.test(e)&&(e="rotate"),r[e]&&(n+=e+"("+r[e].join(" ")+") ",delete r[e])})}else{var o,i;f.each(a(e).transformCache,function(t){return o=a(e).transformCache[t],"transformPerspective"===t?(i=o,!0):(9===d&&"rotateZ"===t&&(t="rotate"),void(n+=t+o+" "))}),i&&(n="perspective"+i+" "+n)}C.setPropertyValue(e,"transform",n)}};C.Hooks.register(),C.Normalizations.register(),b.hook=function(e,t,n){var o=r;return e=i(e),f.each(e,function(e,i){if(a(i)===r&&b.init(i),n===r)o===r&&(o=b.CSS.getPropertyValue(i,t));else{var s=b.CSS.setPropertyValue(i,t,n);"transform"===s[0]&&b.CSS.flushTransformCache(i),o=s}}),o};var T=function(){function e(){return s?S.promise||null:l}function o(){function e(e){function p(e,t){var n=r,o=r,a=r;return y.isArray(e)?(n=e[0],!y.isArray(e[1])&&/^[\d-]/.test(e[1])||y.isFunction(e[1])||C.RegEx.isHex.test(e[1])?a=e[1]:(y.isString(e[1])&&!C.RegEx.isHex.test(e[1])||y.isArray(e[1]))&&(o=t?e[1]:u(e[1],s.duration),e[2]!==r&&(a=e[2]))):n=e,t||(o=o||s.easing),y.isFunction(n)&&(n=n.call(i,w,O)),y.isFunction(a)&&(a=a.call(i,w,O)),[n||0,o,a]}function d(e,t){var n,r;return r=(t||"0").toString().toLowerCase().replace(/[%A-z]+$/,function(e){return n=e,""}),n||(n=C.Values.getUnitType(e)),[r,n]}function m(){var e={myParent:i.parentNode||n.body,position:C.getPropertyValue(i,"position"),fontSize:C.getPropertyValue(i,"fontSize")},r=e.position===A.lastPosition&&e.myParent===A.lastParent,o=e.fontSize===A.lastFontSize;A.lastParent=e.myParent,A.lastPosition=e.position,A.lastFontSize=e.fontSize;var s=100,l={};if(o&&r)l.emToPx=A.lastEmToPx,l.percentToPxWidth=A.lastPercentToPxWidth,l.percentToPxHeight=A.lastPercentToPxHeight;else{var u=a(i).isSVG?n.createElementNS("http://www.w3.org/2000/svg","rect"):n.createElement("div");b.init(u),e.myParent.appendChild(u),f.each(["overflow","overflowX","overflowY"],function(e,t){b.CSS.setPropertyValue(u,t,"hidden")}),b.CSS.setPropertyValue(u,"position",e.position),b.CSS.setPropertyValue(u,"fontSize",e.fontSize),b.CSS.setPropertyValue(u,"boxSizing","content-box"),f.each(["minWidth","maxWidth","width","minHeight","maxHeight","height"],function(e,t){b.CSS.setPropertyValue(u,t,s+"%")}),b.CSS.setPropertyValue(u,"paddingLeft",s+"em"),l.percentToPxWidth=A.lastPercentToPxWidth=(parseFloat(C.getPropertyValue(u,"width",null,!0))||1)/s,l.percentToPxHeight=A.lastPercentToPxHeight=(parseFloat(C.getPropertyValue(u,"height",null,!0))||1)/s,l.emToPx=A.lastEmToPx=(parseFloat(C.getPropertyValue(u,"paddingLeft"))||1)/s,e.myParent.removeChild(u)}return null===A.remToPx&&(A.remToPx=parseFloat(C.getPropertyValue(n.body,"fontSize"))||16),null===A.vwToPx&&(A.vwToPx=parseFloat(t.innerWidth)/100,A.vhToPx=parseFloat(t.innerHeight)/100),l.remToPx=A.remToPx,l.vwToPx=A.vwToPx,l.vhToPx=A.vhToPx,b.debug>=1&&console.log("Unit ratios: "+JSON.stringify(l),i),l}if(s.begin&&0===w)try{s.begin.call(h,h)}catch(P){setTimeout(function(){throw P},1)}if("scroll"===k){var T,x,E,N=/^x$/i.test(s.axis)?"Left":"Top",j=parseFloat(s.offset)||0;s.container?y.isWrapped(s.container)||y.isNode(s.container)?(s.container=s.container[0]||s.container,T=s.container["scroll"+N],E=T+f(i).position()[N.toLowerCase()]+j):s.container=null:(T=b.State.scrollAnchor[b.State["scrollProperty"+N]],x=b.State.scrollAnchor[b.State["scrollProperty"+("Left"===N?"Top":"Left")]],E=f(i).offset()[N.toLowerCase()]+j),l={scroll:{rootPropertyValue:!1,startValue:T,currentValue:T,endValue:E,unitType:"",easing:s.easing,scrollData:{container:s.container,direction:N,alternateValue:x}},element:i},b.debug&&console.log("tweensContainer (scroll): ",l.scroll,i)}else if("reverse"===k){if(!a(i).tweensContainer)return void f.dequeue(i,s.queue);"none"===a(i).opts.display&&(a(i).opts.display="auto"),"hidden"===a(i).opts.visibility&&(a(i).opts.visibility="visible"),a(i).opts.loop=!1,a(i).opts.begin=null,a(i).opts.complete=null,g.easing||delete s.easing,g.duration||delete s.duration,s=f.extend({},a(i).opts,s);var _=f.extend(!0,{},a(i).tweensContainer);for(var M in _)if("element"!==M){var D=_[M].startValue;_[M].startValue=_[M].currentValue=_[M].endValue,_[M].endValue=D,y.isEmptyObject(g)||(_[M].easing=s.easing),b.debug&&console.log("reverse tweensContainer ("+M+"): "+JSON.stringify(_[M]),i)}l=_}else if("start"===k){var _;a(i).tweensContainer&&a(i).isAnimating===!0&&(_=a(i).tweensContainer),f.each(v,function(e,t){if(RegExp("^"+C.Lists.colors.join("$|^")+"$").test(e)){var n=p(t,!0),o=n[0],i=n[1],a=n[2];if(C.RegEx.isHex.test(o)){for(var s=["Red","Green","Blue"],l=C.Values.hexToRgb(o),u=a?C.Values.hexToRgb(a):r,c=0;c<s.length;c++){var f=[l[c]];i&&f.push(i),u!==r&&f.push(u[c]),v[e+s[c]]=f}delete v[e]}}});for(var V in v){var I=p(v[V]),F=I[0],R=I[1],K=I[2];V=C.Names.camelCase(V);var W=C.Hooks.getRoot(V),H=!1;if(a(i).isSVG||"tween"===W||C.Names.prefixCheck(W)[1]!==!1||C.Normalizations.registered[W]!==r){(s.display!==r&&null!==s.display&&"none"!==s.display||s.visibility!==r&&"hidden"!==s.visibility)&&/opacity|filter/.test(V)&&!K&&0!==F&&(K=0),s._cacheValues&&_&&_[V]?(K===r&&(K=_[V].endValue+_[V].unitType),H=a(i).rootPropertyValueCache[W]):C.Hooks.registered[V]?K===r?(H=C.getPropertyValue(i,W),K=C.getPropertyValue(i,V,H)):H=C.Hooks.templates[W][1]:K===r&&(K=C.getPropertyValue(i,V));var z,U,B,Y=!1;if(z=d(V,K),K=z[0],B=z[1],z=d(V,F),F=z[0].replace(/^([+-\/*])=/,function(e,t){return Y=t,""}),U=z[1],K=parseFloat(K)||0,F=parseFloat(F)||0,"%"===U&&(/^(fontSize|lineHeight)$/.test(V)?(F/=100,U="em"):/^scale/.test(V)?(F/=100,U=""):/(Red|Green|Blue)$/i.test(V)&&(F=F/100*255,U="")),/[\/*]/.test(Y))U=B;else if(B!==U&&0!==K)if(0===F)U=B;else{o=o||m();var q=/margin|padding|left|right|width|text|word|letter/i.test(V)||/X$/.test(V)||"x"===V?"x":"y";switch(B){case"%":K*="x"===q?o.percentToPxWidth:o.percentToPxHeight;break;case"px":break;default:K*=o[B+"ToPx"]}switch(U){case"%":K*=1/("x"===q?o.percentToPxWidth:o.percentToPxHeight);break;case"px":break;default:K*=1/o[U+"ToPx"]}}switch(Y){case"+":F=K+F;break;case"-":F=K-F;break;case"*":F=K*F;break;case"/":F=K/F}l[V]={rootPropertyValue:H,startValue:K,currentValue:K,endValue:F,unitType:U,easing:R},b.debug&&console.log("tweensContainer ("+V+"): "+JSON.stringify(l[V]),i)}else b.debug&&console.log("Skipping ["+W+"] due to a lack of browser support.")}l.element=i}l.element&&(C.Values.addClass(i,"velocity-animating"),L.push(l),""===s.queue&&(a(i).tweensContainer=l,a(i).opts=s),a(i).isAnimating=!0,w===O-1?(b.State.calls.push([L,h,s,null,S.resolver]),b.State.isTicking===!1&&(b.State.isTicking=!0,c())):w++)}var o,i=this,s=f.extend({},b.defaults,g),l={};switch(a(i)===r&&b.init(i),parseFloat(s.delay)&&s.queue!==!1&&f.queue(i,s.queue,function(e){b.velocityQueueEntryFlag=!0,a(i).delayTimer={setTimeout:setTimeout(e,parseFloat(s.delay)),next:e}}),s.duration.toString().toLowerCase()){case"fast":s.duration=200;break;case"normal":s.duration=m;break;case"slow":s.duration=600;break;default:s.duration=parseFloat(s.duration)||1}b.mock!==!1&&(b.mock===!0?s.duration=s.delay=1:(s.duration*=parseFloat(b.mock)||1,s.delay*=parseFloat(b.mock)||1)),s.easing=u(s.easing,s.duration),s.begin&&!y.isFunction(s.begin)&&(s.begin=null),s.progress&&!y.isFunction(s.progress)&&(s.progress=null),s.complete&&!y.isFunction(s.complete)&&(s.complete=null),s.display!==r&&null!==s.display&&(s.display=s.display.toString().toLowerCase(),"auto"===s.display&&(s.display=b.CSS.Values.getDisplayType(i))),s.visibility!==r&&null!==s.visibility&&(s.visibility=s.visibility.toString().toLowerCase()),s.mobileHA=s.mobileHA&&b.State.isMobile&&!b.State.isGingerbread,s.queue===!1?s.delay?setTimeout(e,s.delay):e():f.queue(i,s.queue,function(t,n){return n===!0?(S.promise&&S.resolver(h),!0):(b.velocityQueueEntryFlag=!0,void e(t))}),""!==s.queue&&"fx"!==s.queue||"inprogress"===f.queue(i)[0]||f.dequeue(i)}var s,l,d,h,v,g,P=arguments[0]&&(arguments[0].p||f.isPlainObject(arguments[0].properties)&&!arguments[0].properties.names||y.isString(arguments[0].properties));if(y.isWrapped(this)?(s=!1,d=0,h=this,l=this):(s=!0,d=1,h=P?arguments[0].elements||arguments[0].e:arguments[0]),h=i(h)){P?(v=arguments[0].properties||arguments[0].p,g=arguments[0].options||arguments[0].o):(v=arguments[d],g=arguments[d+1]);var O=h.length,w=0;if(!/^(stop|finish|finishAll)$/i.test(v)&&!f.isPlainObject(g)){var x=d+1;g={};for(var E=x;E<arguments.length;E++)y.isArray(arguments[E])||!/^(fast|normal|slow)$/i.test(arguments[E])&&!/^\d/.test(arguments[E])?y.isString(arguments[E])||y.isArray(arguments[E])?g.easing=arguments[E]:y.isFunction(arguments[E])&&(g.complete=arguments[E]):g.duration=arguments[E]}var S={promise:null,resolver:null,rejecter:null};s&&b.Promise&&(S.promise=new b.Promise(function(e,t){S.resolver=e,S.rejecter=t}));var k;switch(v){case"scroll":k="scroll";break;case"reverse":k="reverse";break;case"finish":case"finishAll":case"stop":f.each(h,function(e,t){a(t)&&a(t).delayTimer&&(clearTimeout(a(t).delayTimer.setTimeout),a(t).delayTimer.next&&a(t).delayTimer.next(),delete a(t).delayTimer),"finishAll"!==v||g!==!0&&!y.isString(g)||(f.each(f.queue(t,y.isString(g)?g:""),function(e,t){y.isFunction(t)&&t()}),f.queue(t,y.isString(g)?g:"",[]))});var N=[];return f.each(b.State.calls,function(e,t){t&&f.each(t[1],function(n,o){var i=g===r?"":g;return i!==!0&&t[2].queue!==i&&(g!==r||t[2].queue!==!1)||void f.each(h,function(n,r){r===o&&((g===!0||y.isString(g))&&(f.each(f.queue(r,y.isString(g)?g:""),function(e,t){y.isFunction(t)&&t(null,!0)}),f.queue(r,y.isString(g)?g:"",[])),"stop"===v?(a(r)&&a(r).tweensContainer&&i!==!1&&f.each(a(r).tweensContainer,function(e,t){t.endValue=t.currentValue}),N.push(e)):"finish"!==v&&"finishAll"!==v||(t[2].duration=1))})})}),"stop"===v&&(f.each(N,function(e,t){p(t,!0)}),S.promise&&S.resolver(h)),e();default:if(!f.isPlainObject(v)||y.isEmptyObject(v)){if(y.isString(v)&&b.Redirects[v]){var j=f.extend({},g),_=j.duration,M=j.delay||0;return j.backwards===!0&&(h=f.extend(!0,[],h).reverse()),f.each(h,function(e,t){parseFloat(j.stagger)?j.delay=M+parseFloat(j.stagger)*e:y.isFunction(j.stagger)&&(j.delay=M+j.stagger.call(t,e,O)),j.drag&&(j.duration=parseFloat(_)||(/^(callout|transition)/.test(v)?1e3:m),j.duration=Math.max(j.duration*(j.backwards?1-e/O:(e+1)/O),.75*j.duration,200)),b.Redirects[v].call(t,t,j||{},e,O,h,S.promise?S:r)}),e()}var D="Velocity: First argument ("+v+") was not a property map, a known action, or a registered redirect. Aborting.";return S.promise?S.rejecter(new Error(D)):console.log(D),e()}k="start"}var A={lastParent:null,lastPosition:null,lastFontSize:null,lastPercentToPxWidth:null,lastPercentToPxHeight:null,lastEmToPx:null,remToPx:null,vwToPx:null,vhToPx:null},L=[];f.each(h,function(e,t){y.isNode(t)&&o.call(t)});var V,j=f.extend({},b.defaults,g);if(j.loop=parseInt(j.loop),V=2*j.loop-1,j.loop)for(var I=0;I<V;I++){var F={delay:j.delay,progress:j.progress};I===V-1&&(F.display=j.display,F.visibility=j.visibility,F.complete=j.complete),T(h,"reverse",F)}return e()}};b=f.extend(T,b),b.animate=T;var O=t.requestAnimationFrame||h;return b.State.isMobile||n.hidden===r||n.addEventListener("visibilitychange",function(){n.hidden?(O=function(e){return setTimeout(function(){e(!0)},16)},c()):O=t.requestAnimationFrame||h}),e.Velocity=b,e!==t&&(e.fn.velocity=T,e.fn.velocity.defaults=b.defaults),f.each(["Down","Up"],function(e,t){b.Redirects["slide"+t]=function(e,n,o,i,a,s){var l=f.extend({},n),u=l.begin,c=l.complete,p={height:"",marginTop:"",marginBottom:"",paddingTop:"",paddingBottom:""},d={};l.display===r&&(l.display="Down"===t?"inline"===b.CSS.Values.getDisplayType(e)?"inline-block":"block":"none"),l.begin=function(){u&&u.call(a,a);for(var n in p){d[n]=e.style[n];var r=b.CSS.getPropertyValue(e,n);p[n]="Down"===t?[r,0]:[0,r]}d.overflow=e.style.overflow,e.style.overflow="hidden"},l.complete=function(){for(var t in d)e.style[t]=d[t];c&&c.call(a,a),s&&s.resolver(a)},b(e,p,l)}}),f.each(["In","Out"],function(e,t){b.Redirects["fade"+t]=function(e,n,o,i,a,s){var l=f.extend({},n),u={opacity:"In"===t?1:0},c=l.complete;o!==i-1?l.complete=l.begin=null:l.complete=function(){c&&c.call(a,a),s&&s.resolver(a)},l.display===r&&(l.display="In"===t?"auto":"none"),b(this,u,l)}}),b}(window.jQuery||window.Zepto||window,window,document)})},3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,function(e,t,n,r){"use strict";n(3),n(r)},function(e,t,n,r){"use strict";n(3),n(r),n(23)},function(e,t,n,r){"use strict";n(3),n(r),n(42)}]))}); //# sourceMappingURL=antd.min.js.map
src/routes/notFound/NotFound.js
fvalencia/react-vimeo
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './NotFound.css'; class NotFound extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>{this.props.title}</h1> <p>Sorry, the page you were trying to view does not exist.</p> </div> </div> ); } } export default withStyles(s)(NotFound);
src/routes/Poker/components/PlayerOptions/PlayerOptions.js
GKotsovos/WebPoker
import React, { PropTypes, Component } from 'react'; import classnames from 'classnames'; import Styles from 'styles/main.scss'; export class PlayerOptions extends Component{ render(){ const { player, fold, check, call, bid, leave } = this.props; return ( <div className="form-group"> { (player.move != 'waiting') && (player.move != 'fold') ? [ <div className={Styles['options' + player.id]}> <h3>{`Money: ${player.money}`}</h3> <div> <input type="text" className={`form-control ${Styles.input}`} ref={ node => { this.amount = node }} /> <button type="button" className="btn btn-default" onClick={() => { bid({ id: player.id, amount: Number(this.amount.value) }) this.amount.value = ''; }} >Bid</button> </div> <button type="button" className="btn btn-default" onClick={() => fold(player.id)} >Fold</button> <button type="button" className="btn btn-default" onClick={() => check(player.id)} >Check</button> <button type="button" className="btn btn-default" onClick={() => call(player.id)} >Call</button> </div> ] : <button type="button" className={`btn btn-default ${Styles['player' + player.id]}`} onClick={() => leave(player.id)} >Leave</button> } </div> ) } } PlayerOptions.propTypes = { player: PropTypes.object.isRequired, fold: PropTypes.func.isRequired, check: PropTypes.func.isRequired, call: PropTypes.func.isRequired, bid: PropTypes.func.isRequired, leave: PropTypes.func.isRequired }; export default PlayerOptions;
node_modules/react-icons/md/surround-sound.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const MdSurroundSound = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m20 16.6c1.8 0 3.4 1.6 3.4 3.4s-1.6 3.4-3.4 3.4-3.4-1.6-3.4-3.4 1.6-3.4 3.4-3.4z m9.5 12.9c2.5-2.6 3.9-6.1 3.9-9.5s-1.4-6.9-3.9-9.5l-2.5 2.5c2 1.9 3 4.4 3 7s-0.9 5.2-2.9 7.1z m-9.5-2.9c3.7 0 6.6-2.9 6.6-6.6s-2.9-6.6-6.6-6.6-6.6 2.9-6.6 6.6 2.9 6.6 6.6 6.6z m-7 0.4c-2-1.9-3-4.4-3-7s0.9-5.2 2.9-7.1l-2.4-2.4c-2.5 2.6-3.9 6.1-3.9 9.5s1.4 6.9 3.9 9.5z m20.4-20.4c1.8 0 3.2 1.6 3.2 3.4v20c0 1.8-1.4 3.4-3.2 3.4h-26.8c-1.8 0-3.2-1.6-3.2-3.4v-20c0-1.8 1.4-3.4 3.2-3.4h26.8z"/></g> </Icon> ) export default MdSurroundSound
tests/site6/src/nav/nav.js
dominikwilkowski/cuttlebelle
import PropTypes from 'prop-types'; import React from 'react'; /** * Navigation for use in other components * * @disable-docs */ const Navigation = ({ nav = {}, pages = {}, ID = '', startID = '', relativeURL = ( URL ) => URL, noParents = false, level = 0, childnav1lvl = false, homepageName = '', wrappingId = '', wrappingClass = 'navigation', itemClass = 'navigation__item', nestedItemClass = 'navigation__item--has-nested', levelClass = 'navigation--level-', ancorClass = 'navigation__item__anchor', spanClass = 'navigation__item__span', noanchorClass = 'navigation__item--noanchor', }) => ( <ul { ...( wrappingId && { id: wrappingId } ) } className={`${ wrappingClass } ${ levelClass }${ level }`}> { Object.keys( nav ) .filter( ( key ) => pages[ key ].hidden === undefined || pages[ key ].hidden === false ) // hiding pages that have hidden set to not false .sort( ( keyA, keyB ) => pages[ keyA ].weight - pages[ keyB ].weight ) // sort by weight .map( ( pageID, i ) => { const homepage = homepageName === '' ? Object.keys( nav )[ 0 ] : homepageName; const page = nav[ pageID ]; const _displayItem = noParents && (pageID.startsWith( startID ) && (pageID.charAt(startID.length) == '' || pageID.charAt(startID.length) == '/') ) || level === 2 && childnav1lvl === true || !noParents; // We only pursue this element if it either // starts with our startID or is the homepage if we got noParents = true // But we will only print the name of the element if the element starts with startID and noParents = true if( typeof page === 'object' ) { if( _displayItem || noParents && startID.startsWith( pageID ) || noParents && pageID === homepage ) { return <li className={`${ itemClass } ${ nestedItemClass }`} key={ i }> { _displayItem ? <NavigationItem href={ relativeURL( pages[ pageID ]._url, ID ) } title={ pages[ pageID ].pagetitle } thisPage={ pageID === ID } itemClass={ itemClass } ancorClass={ ancorClass } spanClass={ spanClass } /> : null } <Navigation nav={ page } pages={ pages } ID={ ID } startID={ startID } relativeURL={ relativeURL } noParents={ noParents } level={ level + 1 } childnav1lvl={ childnav1lvl } homepageName={ homepage } wrappingClass={ wrappingClass } itemClass={ itemClass } nestedItemClass={ nestedItemClass } levelClass={ levelClass } ancorClass={ ancorClass } spanClass={ spanClass } noanchorClass={ noanchorClass } /> </li> } } else { // Check to see if this is a childnav placed on 1 level only and add the parent item on the first item if (childnav1lvl == true && level === 2 && i === 0) { const parentId = pageID.substring(0, pageID.indexOf('/')); const parent = pages[parentId]; return <li key={ i } className={ itemClass }> <NavigationItem href={ relativeURL( pages[ page ]._url, ID ) } title={ pages[ page ].pagetitle } thisPage={ page === ID } itemClass={ itemClass } ancorClass={ ancorClass } spanClass={ spanClass } childnav1lvl={ childnav1lvl } /> </li> }else if( _displayItem ) { return <li className={ itemClass } key={ i }> <NavigationItem href={ relativeURL( pages[ page ]._url, ID ) } title={ pages[ page ].pagetitle } thisPage={ page === ID } itemClass={ itemClass } ancorClass={ ancorClass } spanClass={ spanClass } childnav1lvl={ childnav1lvl } /> </li> } } }) } </ul> ); const NavigationItem = ({ itemClass, ancorClass, spanClass, href, title, thisPage, index, childnav1lvl }) => { if( thisPage ) { return <span className={ spanClass }>{ title }</span>; } else { return <a className={ ancorClass } href={ href }>{ title }</a> } }; export default Navigation;
src/encoded/static/components/item-pages/ExperimentSetView.js
hms-dbmi/fourfront
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import _ from 'underscore'; import memoize from 'memoize-one'; import Collapse from 'react-bootstrap/esm/Collapse'; import { FlexibleDescriptionBox } from '@hms-dbmi-bgm/shared-portal-components/es/components/ui/FlexibleDescriptionBox'; import { console, object, isServerSide, layout, commonFileUtil, schemaTransforms, logger } from '@hms-dbmi-bgm/shared-portal-components/es/components/util'; import { expFxn, Schemas, typedefs } from './../util'; import { HiGlassAjaxLoadContainer } from './components/HiGlass/HiGlassAjaxLoadContainer'; import { HiGlassPlainContainer, isHiglassViewConfigItem } from './components/HiGlass/HiGlassPlainContainer'; import { AdjustableDividerRow } from './components/AdjustableDividerRow'; import { OverviewHeadingContainer } from './components/OverviewHeadingContainer'; import { OverViewBodyItem } from './DefaultItemView'; import WorkflowRunTracingView, { FileViewGraphSection } from './WorkflowRunTracingView'; import { QCMetricFromSummary } from './QualityMetricView'; import { RawFilesStackedTableExtendedColumns, ProcessedFilesStackedTable, renderFileQCReportLinkButton, renderFileQCDetailLinkButton } from './../browse/components/file-tables'; import { SelectedFilesController, uniqueFileCount } from './../browse/components/SelectedFilesController'; import { SelectedFilesDownloadButton } from './../browse/components/above-table-controls/SelectedFilesDownloadButton'; import { EmbeddedHiglassActions } from './../static-pages/components'; import { combineExpsWithReplicateNumbersForExpSet } from './../util/experiments-transforms'; import { StackedBlockTable, StackedBlock, StackedBlockList, StackedBlockName, StackedBlockNameLabel } from '@hms-dbmi-bgm/shared-portal-components/es/components/browse/components/StackedBlockTable'; // eslint-disable-next-line no-unused-vars const { Item, File, ExperimentSet } = typedefs; // import { SET } from './../testdata/experiment_set/replicate_4DNESDG4HNP9'; // import { SET } from './../testdata/experiment_set/replicate_with_bigwigs'; /** * ExperimentSet Item view/page. * * @prop {Object} schemas - state.schemas passed down from app Component. * @prop {ExperimentSet} context - JSON representation of current ExperimentSet item. */ export default class ExperimentSetView extends WorkflowRunTracingView { static shouldShowSupplementaryFilesTabView = memoize(function(context){ const opfCollections = SupplementaryFilesTabView.combinedOtherProcessedFiles(context); const referenceFiles = SupplementaryFilesTabView.allReferenceFiles(context); return (opfCollections.length > 0 || referenceFiles.length > 0); }); /** Preserve selected files if href changes (due to `#tab-id`), unlike the default setting for BrowseView. */ static resetSelectedFilesCheck(nextProps, pastProps){ if (nextProps.context !== pastProps.context) return true; return false; } static propTypes = { 'schemas' : PropTypes.object, 'context' : PropTypes.object.isRequired }; constructor(props){ super(props); _.bindAll(this, 'isWorkflowNodeCurrentContext', 'getTabViewContents', 'shouldGraphExist'); this.allProcessedFilesFromExperimentSet = memoize(expFxn.allProcessedFilesFromExperimentSet); this.allFilesFromExperimentSet = memoize(expFxn.allFilesFromExperimentSet); /** * Explicit self-assignment to remind that we inherit the following properties from WorkfowRunTracingView: * `loadingGraphSteps`, `allRuns`, `steps`, & `mounted` */ this.state = this.state; } shouldGraphExist(){ const { context } = this.props; const processedFiles = this.allProcessedFilesFromExperimentSet(context); const processedFilesLen = (processedFiles && processedFiles.length) || 0; return processedFilesLen > 0; } isWorkflowNodeCurrentContext(node){ var ctx = this.props.context; if (!ctx) return false; if (!node || !node.meta || !node.meta.run_data || !node.meta.run_data.file) return false; if (Array.isArray(node.meta.run_data.file)) return false; if (typeof node.meta.run_data.file.accession !== 'string') return false; if (!ctx.processed_files || !Array.isArray(ctx.processed_files) || ctx.processed_files.length === 0) return false; if (_.contains(_.pluck(ctx.processed_files, 'accession'), node.meta.run_data.file.accession)) return true; return false; } /** * Executed on width change, as well as this ItemView's prop change. */ getTabViewContents(){ const { context, schemas, windowWidth, windowHeight, href, session } = this.props; const { mounted } = this.state; //context = SET; // Use for testing along with _testing_data const processedFiles = this.allProcessedFilesFromExperimentSet(context); const processedFilesLen = (processedFiles && processedFiles.length) || 0; const rawFiles = this.allFilesFromExperimentSet(context, false); const rawFilesLen = (rawFiles && rawFiles.length) || 0; const width = this.getTabViewWidth(); const commonProps = { width, context, schemas, windowWidth, href, session, mounted }; const propsForTableSections = _.extend(SelectedFilesController.pick(this.props), commonProps); var tabs = []; // Processed Files Table Tab if (processedFilesLen > 0){ tabs.push({ tab : <span><i className="icon icon-microchip fas icon-fw"/>{ ' ' + processedFilesLen + " Processed File" + (processedFilesLen > 1 ? 's' : '') }</span>, key : 'processed-files', content : ( <SelectedFilesController resetSelectedFilesCheck={ExperimentSetView.resetSelectedFilesCheck} initiallySelectedFiles={processedFiles}> <ProcessedFilesStackedTableSection {...propsForTableSections} files={processedFiles} /> </SelectedFilesController> ) }); } // Raw files tab, if have experiments with raw files if (rawFilesLen > 0){ tabs.push({ tab : <span><i className="icon icon-leaf fas icon-fw"/>{ ' ' + rawFilesLen + " Raw File" + (rawFilesLen > 1 ? 's' : '') }</span>, key : 'raw-files', content : ( <SelectedFilesController resetSelectedFilesCheck={ExperimentSetView.resetSelectedFilesCheck} initiallySelectedFiles={rawFiles}> <RawFilesStackedTableSection {...propsForTableSections} files={rawFiles} /> </SelectedFilesController> ) }); } // Graph Section Tab if (this.shouldGraphExist()){ tabs.push(FileViewGraphSection.getTabObject( _.extend({}, this.props, { 'isNodeCurrentContext' : this.isWorkflowNodeCurrentContext }), this.state, this.handleToggleAllRuns, width )); } // Supplementary Files Tab if (ExperimentSetView.shouldShowSupplementaryFilesTabView(context)){ //const referenceFiles = SupplementaryFilesTabView.allReferenceFiles(context) || []; //const opfCollections = SupplementaryFilesTabView.combinedOtherProcessedFiles(context) || []; //const allOpfFiles = _.reduce(opfCollections, function (memo, coll) { return memo.concat(coll.files || []); }, []); //const allFiles = referenceFiles.concat(allOpfFiles); tabs.push({ tab : <span><i className="icon icon-copy far icon-fw"/> Supplementary Files</span>, key : 'supplementary-files', content: ( <SelectedFilesController resetSelectedFilesCheck={ExperimentSetView.resetSelectedFilesCheck} initiallySelectedFiles={[]/*allFiles*/}> <SupplementaryFilesTabView {...propsForTableSections} {...this.state} /> </SelectedFilesController> ) }); } return _.map(tabs.concat(this.getCommonTabs()), function(tabObj){ return _.extend(tabObj, { 'style' : { 'minHeight' : Math.max(mounted && !isServerSide() && (windowHeight - 180), 100) || 800 } }); }); } itemMidSection(){ const { context, schemas } = this.props; return ( <React.Fragment> { super.itemMidSection() } <OverviewHeading context={context} schemas={schemas} key="overview" className="with-background mb-2 mt-1" title="Experiment Set Properties" prependTitleIcon prependTitleIconFxn={prependOverviewHeadingTitleIcon} /> </React.Fragment> ); } } const OverviewHeading = React.memo(function OverviewHeading(props){ const { context, schemas } = props; const tips = object.tipsFromSchema(schemas, context); const commonProps = { 'result' : context, 'tips' : tips, 'wrapInColumn' : 'col-sm-6 col-md-3' }; return ( <OverviewHeadingContainer {...props}> {/* <OverViewBodyItem result={expSet} tips={tips} property='award.project' fallbackTitle="Project" wrapInColumn={col} /> */} <OverViewBodyItem {...commonProps} property="experimentset_type" fallbackTitle="Set Type" /> <OverViewBodyItem {...commonProps} property="experiments_in_set.biosample.biosource.individual.organism" fallbackTitle="Organism" /> <OverViewBodyItem {...commonProps} property="experiments_in_set.biosample.biosource.biosource_type" fallbackTitle="Biosource Type" /> <OverViewBodyItem {...commonProps} property="experiments_in_set.biosample.biosource_summary" fallbackTitle="Biosource" /> <OverViewBodyItem {...commonProps} property="experiments_in_set.experiment_type" fallbackTitle="Experiment Type(s)" /> <OverViewBodyItem {...commonProps} property="experiments_in_set.biosample.modifications.modification_type" fallbackTitle="Modification Type" /> <OverViewBodyItem {...commonProps} property="experiments_in_set.biosample.treatments.treatment_type" fallbackTitle="Treatment Type" /> <OverViewBodyItem {...commonProps} property="experiments_in_set.experiment_categorizer.combined" fallbackTitle="Assay Details" titleRenderFxn={OverviewHeading.expCategorizerTitle} wrapInColumn="col-sm-6 col-md-3 pull-right" /> <OverViewBodyItem {...commonProps} property="sample_image" fallbackTitle="Sample Image" wrapInColumn="col-sm-6 col-md-3" singleItemClassName="block" titleRenderFxn={OverViewBodyItem.titleRenderPresets.embedded_item_with_image_attachment} hideIfNoValue /> <OverViewBodyItem {...commonProps} property="imaging_paths" fallbackTitle="Imaging Paths" wrapInColumn="col-sm-6 col-md-9" listItemElement="div" listWrapperElement="div" singleItemClassName="block" titleRenderFxn={OverViewBodyItem.titleRenderPresets.imaging_paths_from_exp} hideIfNoValue /> </OverviewHeadingContainer> ); }); // eslint-disable-next-line react/display-name function prependOverviewHeadingTitleIcon(open, props){ return <i className="expand-icon icon icon-list icon-fw fas" />; } const expCategorizerTitleRenderFxn = memoize(function(field, val, allowJX = true, includeDescriptionTips = true, index = null, wrapperElementType = 'li', fullObject = null){ let expCatObj = _.uniq(object.getNestedProperty(fullObject, 'experiments_in_set.experiment_categorizer'), false, 'combined'); expCatObj = (Array.isArray(expCatObj) && expCatObj.length === 1 && expCatObj[0]) || expCatObj; if (expCatObj && expCatObj.combined && expCatObj.field && typeof expCatObj.value !== 'undefined'){ return <span><span className="text-500">{ expCatObj.field }:</span> { expCatObj.value }</span>; } return OverViewBodyItem.titleRenderPresets.default(...arguments); }); export class RawFilesStackedTableSection extends React.PureComponent { static selectedFilesUniqueCount = memoize(uniqueFileCount); renderHeader(){ const { context, files, selectedFiles, session } = this.props; const selectedFilesUniqueCount = RawFilesStackedTableSection.selectedFilesUniqueCount(selectedFiles); const fileCount = files.length; const filenamePrefix = (context.accession || context.display_title) + "_raw_files_"; return ( <h3 className="tab-section-title"> <span className="text-400">{ fileCount }</span>{ ' Raw File' + (fileCount > 1 ? 's' : '')} { selectedFiles ? // Make sure data structure is present (even if empty) <div className="download-button-container pull-right" style={{ marginTop : -10 }}> <SelectedFilesDownloadButton {...{ selectedFiles, filenamePrefix, context, session }} disabled={selectedFilesUniqueCount === 0} id="expset-raw-files-download-files-btn" analyticsAddFilesToCart> <i className="icon icon-download fas icon-fw mr-07 align-baseline"/> <span className="d-none d-sm-inline">Download </span> <span className="count-to-download-integer">{ selectedFilesUniqueCount }</span> <span className="d-none d-sm-inline text-400"> Raw Files</span> </SelectedFilesDownloadButton> </div> : null } </h3> ); } render(){ const { context, files } = this.props; const anyFilesWithMetrics = !!(commonFileUtil.filterFilesWithEmbeddedMetricItem(files, true)); return ( <div className="overflow-hidden"> { this.renderHeader() } <div className="exp-table-container"> <RawFilesStackedTableExtendedColumns {..._.extend(_.pick(this.props, 'width', 'windowWidth', 'href'), SelectedFilesController.pick(this.props))} experimentSet={context} showMetricColumns={anyFilesWithMetrics} collapseLongLists={true} collapseLimit={10} collapseShow={7} incrementalExpandLimit={100} incrementalExpandStep={100} analyticsImpressionOnMount /> </div> </div> ); } } /** * TODO: Move to HiGlassTabView.js ? */ class HiGlassAdjustableWidthRow extends React.PureComponent { static propTypes = { 'width' : PropTypes.number.isRequired, 'mounted' : PropTypes.bool.isRequired, 'renderRightPanel' : PropTypes.func, 'windowWidth' : PropTypes.number.isRequired, 'higlassItem' : PropTypes.object, 'minOpenHeight' : PropTypes.number, 'maxOpenHeight' : PropTypes.number, 'renderLeftPanelPlaceholder' : PropTypes.func, 'leftPanelCollapseHeight' : PropTypes.number, 'leftPanelCollapseWidth' : PropTypes.number, 'leftPanelDefaultCollapsed' : PropTypes.bool }; static defaultProps = { 'minOpenHeight' : 300, 'maxOpenHeight' : 800 }; constructor(props){ super(props); _.bindAll(this, 'correctHiGlassTrackDimensions', 'renderLeftPanel'); this.correctHiGlassTrackDimensions = _.debounce(this.correctHiGlassTrackDimensions, 100); this.higlassContainerRef = React.createRef(); } componentDidUpdate(pastProps){ const { width } = this.props; if (pastProps.width !== width){ this.correctHiGlassTrackDimensions(); } } /** * This is required because HiGlass doesn't always update all of own tracks' widths (always updates header, tho) */ correctHiGlassTrackDimensions(){ var internalHiGlassComponent = this.higlassContainerRef.current && this.higlassContainerRef.current.getHiGlassComponent(); if (!internalHiGlassComponent) { console.warn('Internal HiGlass Component not accessible.'); return; } setTimeout(HiGlassPlainContainer.correctTrackDimensions, 10, internalHiGlassComponent); } renderLeftPanel(leftPanelWidth, resetXOffset, collapsed, rightPanelHeight){ const { renderLeftPanelPlaceholder, leftPanelCollapseHeight, higlassItem, minOpenHeight, maxOpenHeight } = this.props; if (collapsed){ var useHeight = leftPanelCollapseHeight || rightPanelHeight || minOpenHeight; if (typeof renderLeftPanelPlaceholder === 'function'){ return renderLeftPanelPlaceholder(leftPanelWidth, resetXOffset, collapsed, useHeight); } else { return ( <h5 className="placeholder-for-higlass text-center clickable mb-0 mt-0" style={{ 'lineHeight': useHeight + 'px', 'height': useHeight }} onClick={resetXOffset} data-html data-place="right" data-tip="Open HiGlass Visualization for file(s)"> <i className="icon icon-fw fas icon-tv"/> </h5> ); } } else { return ( <React.Fragment> <EmbeddedHiglassActions context={higlassItem} showDescription={false} /> <HiGlassAjaxLoadContainer higlassItem={higlassItem} className={collapsed ? 'disabled' : null} height={Math.min(Math.max(rightPanelHeight - 16, minOpenHeight - 16), maxOpenHeight)} ref={this.higlassContainerRef} /> </React.Fragment> ); } } render(){ const { mounted, minOpenHeight, leftPanelCollapseWidth, windowWidth } = this.props; // Don't render the HiGlass view if it isn't mounted yet or there is nothing to display. if (!mounted) { return ( <div className="adjustable-divider-row text-center py-5"> <div className="text-center my-5"> <i className="icon icon-spin icon-circle-notch fas text-secondary icon-2x"/> </div> </div> ); } // Pass (almost) all props down so that re-renders are triggered of AdjustableDividerRow PureComponent const passProps = _.omit(this.props, 'higlassItem', 'minOpenHeight', 'maxOpenHeight', 'leftPanelCollapseWidth'); const rgs = layout.responsiveGridState(windowWidth); const leftPanelDefaultWidth = rgs === 'xl' ? 400 : 300; return ( <AdjustableDividerRow {...passProps} height={minOpenHeight} leftPanelClassName="expset-higlass-panel" leftPanelDefaultWidth={leftPanelDefaultWidth} leftPanelCollapseWidth={leftPanelCollapseWidth || 240} // TODO: Change to 240 after updating to HiGlass version w/ resize viewheader stuff fixed. renderLeftPanel={this.renderLeftPanel} rightPanelClassName="exp-table-container" onDrag={this.correctHiGlassTrackDimensions} /> ); } } class QCMetricsTable extends React.PureComponent { static qcSummaryItemTitleTooltipsByTitle(fileGroup) { const tooltipsByTitle = {}; fileGroup.forEach(function({ title: qmsTitle, quality_metric_summary: { title_tooltip = null } = {} }){ if (typeof tooltipsByTitle[qmsTitle] === "string") { return; // skip/continue; already found a tooltip_title for this qms title. } if (title_tooltip && typeof title_tooltip === "string"){ tooltipsByTitle[qmsTitle] = title_tooltip; } }); return tooltipsByTitle; } static renderForFileColValue(file) { const fileAtId = file && object.atIdFromObject(file); let fileTitleString; if (file.accession) { fileTitleString = file.accession; } if (!fileTitleString && fileAtId) { var idParts = _.filter(fileAtId.split('/')); if (idParts[1].slice(0, 5) === '4DNFI') { fileTitleString = idParts[1]; } } if (!fileTitleString) { fileTitleString = file.uuid || fileAtId || 'N/A'; } return ( <React.Fragment> <div>{ Schemas.Term.toName("file_type_detailed", file.file_type_detailed, true) }</div> <a className="text-500 name-title" href={fileAtId}> {fileTitleString} </a> </React.Fragment>); } static generateAlignedColumnHeaders(fileGroups){ return fileGroups.map(function(fileGroup){ const titleTooltipsByQMSTitle = QCMetricsTable.qcSummaryItemTitleTooltipsByTitle(fileGroup); const columnHeaders = [ // Static / present-for-each-table headers { columnClass: 'experiment', title: 'Experiment', initialWidth: 145, className: 'text-left' }, { columnClass: 'file', className: 'double-height-block', title: 'For File', initialWidth: 100, render: QCMetricsTable.renderForFileColValue } ].concat(fileGroup[0].quality_metric.quality_metric_summary.map(function(qmsObj, qmsIndex){ // Dynamic Headers const { title, title_tooltip } = qmsObj; // title tooltip: if missing in the first item then try to get it from the first valid one in array return { columnClass: 'file-detail', title, title_tooltip: title_tooltip || titleTooltipsByQMSTitle[title] || null, initialWidth: 80, render: function renderColHeaderValue(file, field, colIndex, fileEntryBlockProps) { const qmsItem = file.quality_metric.quality_metric_summary[qmsIndex]; const { value, tooltip } = QCMetricFromSummary.formatByNumberType(qmsItem); return <span className="d-inline-block" data-tip={tooltip}>{value}</span>; } }; })); // Add 'Link to Report' column, if any files w/ one. Else include blank one so columns align with any other stacked ones. const anyFilesWithMetricURL = _.any(fileGroup, function (f) { return f && f.quality_metric && f.quality_metric.url; }); if (anyFilesWithMetricURL) { columnHeaders.push({ columnClass: 'file-detail', title: 'Report', initialWidth: 35, render: renderFileQCReportLinkButton }); columnHeaders.push({ columnClass: 'file-detail', title: 'Details', initialWidth: 35, render: renderFileQCDetailLinkButton }); } else { columnHeaders.push({ columnClass: 'file-detail', title: 'Details', initialWidth: 50, render: renderFileQCDetailLinkButton }); } return columnHeaders; }); } /** * commonFileUtil.groupFilesByQCSummaryTitles function is wrapped to allow * custom sorting by QC schema's qc_order and @type Atacseq or Chipseq specific QCS items */ static groupFilesByQCSummaryTitles(filesWithMetrics, schemas) { let filesByTitles = commonFileUtil.groupFilesByQCSummaryTitles(filesWithMetrics); const comparerFunc = (filesA, filesB) => { const [fileA] = filesA; //assumption: 1st file's QC is adequate to define order const [fileB] = filesB; //assumption: 1st file's QC is adequate to define order let orderA, orderB; if (schemas) { const itemTypeA = schemaTransforms.getItemType(fileA.quality_metric); if (itemTypeA && schemas[itemTypeA]) { const { qc_order } = schemas[itemTypeA]; if (typeof qc_order === 'number') { orderA = qc_order; } } const itemTypeB = schemaTransforms.getItemType(fileB.quality_metric); if (itemTypeB && schemas[itemTypeB]) { const { qc_order } = schemas[itemTypeB]; if (typeof qc_order === 'number') { orderB = qc_order; } } } if (orderA && orderB && orderA !== orderB) { return orderA - orderB; } //custom comparison for @type Atacseq or Chipseq specific QCS items if (_.any(fileA.quality_metric.quality_metric_summary, (qcs) => qcs.title === 'Nonredundant Read Fraction (NRF)')) { return -1; } else if (_.any(fileB.quality_metric.quality_metric_summary, (qcs) => qcs.title === 'Nonredundant Read Fraction (NRF)')) { return 1; } return 0; }; if (filesByTitles) { filesByTitles = filesByTitles.slice(); filesByTitles.sort(comparerFunc); } return filesByTitles; } static defaultProps = { heading: ( <h3 className="tab-section-title mt-12"> <span>Quality Metrics</span> </h3> ) }; constructor(props){ super(props); this.memoized = { filterFilesWithQCSummary: memoize(commonFileUtil.filterFilesWithQCSummary), groupFilesByQCSummaryTitles: memoize(QCMetricsTable.groupFilesByQCSummaryTitles), generateAlignedColumnHeaders: memoize(QCMetricsTable.generateAlignedColumnHeaders) }; } render() { const { width, files, windowWidth, href, heading, schemas } = this.props; const filesWithMetrics = this.memoized.filterFilesWithQCSummary(files); const filesWithMetricsLen = filesWithMetrics.length; if (!filesWithMetrics || filesWithMetricsLen === 0) return null; const filesByTitles = this.memoized.groupFilesByQCSummaryTitles(filesWithMetrics, schemas); const columnHeadersForFileGroups = this.memoized.generateAlignedColumnHeaders(filesByTitles); const commonTableProps = { width, windowWidth, href, collapseLongLists: true, collapseLimit: 10, collapseShow: 7, analyticsImpressionOnMount: false, titleForFiles: "Processed File Metrics", showNotesColumns: 'never' }; return ( <div className="row"> <div className="exp-table-container col-12"> { heading } { filesByTitles.map(function(fileGroup, i){ return ( <ProcessedFilesStackedTable {...commonTableProps} key={i} files={fileGroup} columnHeaders={columnHeadersForFileGroups[i]} /> ); })} </div> </div> ); } } class ProcessedFilesStackedTableSection extends React.PureComponent { /** * Searches the context for HiGlass static_content, and returns the HiGlassItem (except the viewconfig). * * @param {object} context - Object that has static_content. * @return {object} Returns the HiGlassItem in the context (or null if it doesn't) */ static getHiglassItemFromProcessedFiles = memoize(function(context){ if (!Array.isArray(context.static_content)){ return null; } // Return the first appearance of a HiglassViewConfig Item located at "tab:processed-files" const higlassTab = _.find(context.static_content, function(section){ return section.location === "tab:processed-files" && isHiglassViewConfigItem(section.content); }); return (higlassTab ? higlassTab.content : null); }); static tableProps(sectionProps){ return _.extend( _.pick(sectionProps, 'files', 'windowWidth', 'href'), { 'collapseLimit': 10, 'collapseShow': 7, 'incrementalExpandLimit': 100, 'incrementalExpandStep': 100, 'analyticsImpressionOnMount': true }, SelectedFilesController.pick(sectionProps) ); } static selectedFilesUniqueCount = memoize(uniqueFileCount); constructor(props){ super(props); _.bindAll(this, 'renderTopRow', 'renderProcessedFilesTableAsRightPanel'); } renderProcessedFilesTableAsRightPanel(rightPanelWidth, resetDivider, leftPanelCollapsed){ return <ProcessedFilesStackedTable {...ProcessedFilesStackedTableSection.tableProps(this.props)} width={Math.max(rightPanelWidth, 320)} key="p-table" />; } renderTopRow(){ const { mounted, width, context, windowWidth, selectedFiles } = this.props; const higlassItem = ProcessedFilesStackedTableSection.getHiglassItemFromProcessedFiles(context); if (higlassItem && object.itemUtil.atId(higlassItem)){ // selectedFiles passed in to re-render panel if changes. return <HiGlassAdjustableWidthRow {...{ width, mounted, windowWidth, higlassItem, selectedFiles }} renderRightPanel={this.renderProcessedFilesTableAsRightPanel} />; } else { return <ProcessedFilesStackedTable {...ProcessedFilesStackedTableSection.tableProps(this.props)} width={width} key="p-table"/>; } } /** * Mostly clonned from ProcessedFilesStackedTable.defaultProps to render the table * compatible w/ processed file table */ static expsNotAssociatedWithFileColumnHeaders = [ { columnClass: 'experiment', className: 'text-left', title: 'Experiment', initialWidth: 180, render: function (exp) { const nameTitle = (exp && typeof exp.display_title === 'string' && exp.display_title.replace(' - ' + exp.accession, '')) || exp.accession; const experimentAtId = object.atIdFromObject(exp); const replicateNumbersExists = exp && exp.bio_rep_no && exp.tec_rep_no; return ( <StackedBlockName className={replicateNumbersExists ? "double-line" : ""}> {replicateNumbersExists ? <div>Bio Rep <b>{exp.bio_rep_no}</b>, Tec Rep <b>{exp.tec_rep_no}</b></div> : <div />} {experimentAtId ? <a href={experimentAtId} className="name-title text-500">{nameTitle}</a> : <div className="name-title">{nameTitle}</div>} </StackedBlockName> ); } }, { columnClass: 'file', className: 'has-checkbox', title: 'File', initialWidth: 165 }, { columnClass: 'file-detail', className: '', title: 'File Type', initialWidth: 135 }, { columnClass: 'file-detail', className: '', title: 'File Size', initialWidth: 70 } ]; render(){ const { context, session, files, selectedFiles } = this.props; return ( <div className="processed-files-table-section exp-table-section"> <ProcessedFilesTableSectionHeader {...{ context, session, files, selectedFiles }} /> {this.renderTopRow()} <ExperimentsWithoutFilesStackedTable {...this.props} /> <QCMetricsTable {...this.props} /> </div> ); } } const ProcessedFilesTableSectionHeader = React.memo(function ProcessedFilesTableSectionHeader({ files, selectedFiles, context, session }){ const selectedFilesUniqueCount = ProcessedFilesStackedTableSection.selectedFilesUniqueCount(selectedFiles); const filenamePrefix = (context.accession || context.display_title) + "_processed_files_"; return ( <h3 className="tab-section-title"> <span> <span className="text-400">{ files.length }</span> Processed Files </span> { selectedFiles ? // Make sure data structure is present (even if empty) <div className="download-button-container pull-right" style={{ marginTop : -10 }}> <SelectedFilesDownloadButton {...{ selectedFiles, filenamePrefix, context, session }} disabled={selectedFilesUniqueCount === 0} id="expset-processed-files-download-files-btn" analyticsAddFilesToCart> <i className="icon icon-download icon-fw fas mr-07 align-baseline"/> <span className="d-none d-sm-inline">Download </span> <span className="count-to-download-integer">{ selectedFilesUniqueCount }</span> <span className="d-none d-sm-inline text-400"> Processed Files</span> </SelectedFilesDownloadButton> </div> : null } </h3> ); }); const ExperimentsWithoutFilesStackedTable = React.memo(function ExperimentsWithoutFilesStackedTable(props) { const { context } = props; const expsNotAssociatedWithAnyFiles = _.filter(context.experiments_in_set, function (exp) { return !((exp.files && Array.isArray(exp.files) && exp.files.length > 0) || (exp.processed_files && Array.isArray(exp.processed_files) && exp.processed_files.length > 0)); }); if (expsNotAssociatedWithAnyFiles.length === 0) { return null; } const tableProps = { 'columnHeaders': ProcessedFilesStackedTableSection.expsNotAssociatedWithFileColumnHeaders }; const expsWithReplicateExps = expFxn.combineWithReplicateNumbers(context.replicate_exps, expsNotAssociatedWithAnyFiles); const experimentBlock = expsWithReplicateExps.map((exp) => { const content = _.map(ProcessedFilesStackedTableSection.expsNotAssociatedWithFileColumnHeaders, function (col, idx) { if (col.render && typeof col.render === 'function') { return col.render(exp); } else { /** * workaround: We surround div by React.Fragment to prevent 'Warning: React does not recognize the XX prop on a DOM element. If you intentionally want * it to appear in the DOM as a custom attribute, spell it as lowercase $isactive instead.' error, * since StackedBlockTable.js/StackedBlock component injects * some props from parent element into 'div' element assuming it is a React component, in case it is not. */ return ( <React.Fragment> <div className={"col-" + col.columnClass + " item detail-col" + idx} style={{ flex: '1 0 ' + col.initialWidth + 'px' }}>{'-'}</div> </React.Fragment> ); } }); return ( <StackedBlock columnClass="experiment" hideNameOnHover={false} key={exp.accession} label={ <StackedBlockNameLabel title={'Experiment'} accession={exp.accession} subtitleVisible /> }> {content} </StackedBlock> ); }); return ( <div className="experiments-not-having-files"> <div className="stacked-block-table-outer-container overflow-auto"> <StackedBlockTable {..._.omit(props, 'children', 'files')} {...tableProps} className="expset-processed-files"> <StackedBlockList className="sets" collapseLongLists={false}> {experimentBlock} </StackedBlockList> </StackedBlockTable> </div> </div> ); }); class SupplementaryFilesOPFCollection extends React.PureComponent { static collectionStatus = function(files){ const statuses = _.uniq(_.pluck(files, 'status')); const len = statuses.length; if (len === 1){ return statuses[0]; } else if (len > 1) { return statuses; } return null; } static defaultProps = { 'defaultOpen' : false }; constructor(props){ super(props); this.toggleOpen = this.toggleOpen.bind(this); this.renderFilesTable = this.renderFilesTable.bind(this); // Usually have >1 SupplementaryFilesOPFCollection on page so we memoize at instance level not class level. this.collectionStatus = memoize(SupplementaryFilesOPFCollection.collectionStatus); this.state = { 'open' : props.defaultOpen }; } toggleOpen(e){ this.setState(function(oldState){ return { 'open' : !oldState.open }; }); } renderFilesTable(width, resetDividerFxn, leftPanelCollapsed){ const { collection, href } = this.props; const passProps = _.extend({ width, href }, SelectedFilesController.pick(this.props)); return ( <ProcessedFilesStackedTable {...passProps} files={collection.files} collapseLongLists analyticsImpressionOnMount /> ); } renderStatusIndicator(){ const { collection } = this.props; const { files, description } = collection; const status = this.collectionStatus(files); if (!status) return null; const outerClsName = "d-inline-block pull-right mr-12 ml-2 mt-1"; if (typeof status === 'string'){ const capitalizedStatus = Schemas.Term.toName("status", status); return ( <div data-tip={"Status for all files in this collection is " + capitalizedStatus} className={outerClsName}> <i className="item-status-indicator-dot mr-07" data-status={status} /> { capitalizedStatus } </div> ); } else { const capitalizedStatuses = _.map(status, Schemas.Term.toName.bind(null, "status")); return ( <div data-tip={"All files in collection have one of the following statuses - " + capitalizedStatuses.join(', ')} className={outerClsName}> <span className="indicators-collection d-inline-block mr-05"> { _.map(status, function(s){ return <i className="item-status-indicator-dot mr-02" data-status={s} />; }) } </span> Multiple </div> ); } } render(){ const { collection, index, width, mounted, defaultOpen, windowWidth, href, selectedFiles } = this.props; const { files, higlass_view_config, description, title } = collection; const { open } = this.state; const qcMetricsHeading = ( <h4 className="text-500 mt-2 mb-1"> <span>Quality Metrics</span> </h4> ); return ( <div data-open={open} className="supplementary-files-section-part" key={title || 'collection-' + index}> { this.renderStatusIndicator() } <h4> <span className="d-inline-block clickable" onClick={this.toggleOpen}> <i className={"text-normal icon icon-fw fas icon-" + (open ? 'minus' : 'plus')} /> { title || "Collection " + index } <span className="text-normal text-300">({ files.length } file{files.length === 1 ? '' : 's'})</span> </span> </h4> { description ? <FlexibleDescriptionBox description={description} className="description" fitTo="grid" expanded={open} windowWidth={windowWidth} /> : <div className="mb-15"/> } <Collapse in={open} mountOnEnter> <div className="table-for-collection"> { higlass_view_config ? <HiGlassAdjustableWidthRow higlassItem={higlass_view_config} windowWidth={windowWidth} mounted={mounted} width={width - 21} renderRightPanel={this.renderFilesTable} selectedFiles={selectedFiles} leftPanelDefaultCollapsed={defaultOpen === false} /> : this.renderFilesTable(width - 21) } <QCMetricsTable {...{ 'width': width - 20, windowWidth, href, files, 'heading': qcMetricsHeading }} /> </div> </Collapse> </div> ); } } class SupplementaryReferenceFilesSection extends React.PureComponent { static defaultProps = { 'defaultOpen' : true, 'columnHeaders' : (function(){ const colHeaders = ProcessedFilesStackedTable.defaultProps.columnHeaders.slice(); colHeaders.push({ columnClass: 'file-detail', title: 'Status', initialWidth: 30, field : "status", render : function(file, field, detailIndex, fileEntryBlockProps){ const capitalizedStatus = Schemas.Term.toName("status", file.status); return <i className="item-status-indicator-dot" data-status={file.status} data-tip={capitalizedStatus} />; } }); return colHeaders; })() }; constructor(props){ super(props); this.toggleOpen = this.toggleOpen.bind(this); this.state = { 'open' : props.defaultOpen }; } toggleOpen(e){ this.setState(function({ open }){ return { 'open' : !open }; }); } render(){ const { files, width, href, columnHeaders } = this.props; const { open } = this.state; const filesLen = files.length; const passProps = _.extend({ width : width - 21, href, files }, SelectedFilesController.pick(this.props)); return ( <div data-open={open} className="reference-files-section supplementary-files-section-part"> <h4 className="mb-15"> <span className="d-inline-block clickable" onClick={this.toggleOpen}> <i className={"text-normal icon icon-fw fas icon-" + (open ? 'minus' : 'plus')} /> { filesLen + " Reference File" + (filesLen > 1 ? "s" : "") } </span> </h4> <Collapse in={open} mountOnEnter> <div className="table-for-collection"> <ProcessedFilesStackedTable {...passProps} files={files} columnHeaders={columnHeaders} /> </div> </Collapse> </div> ); } } class SupplementaryFilesTabView extends React.PureComponent { static selectedFilesUniqueCount = memoize(uniqueFileCount); /** @returns {boolean} true if at least one file inside the collection is viewable */ static checkOPFCollectionPermission({ files }){ return _.any(files || [], function(file){ return file && object.itemUtil.atId(file) && !file.error; }); } /** @returns {boolean} true if at least one collection has at least one file inside the collection that is viewable */ static checkOPFCollectionsPermissions(opfCollections){ return _.any(opfCollections || [], SupplementaryFilesTabView.checkOPFCollectionPermission); } /** * Combines files from ExperimentSet.other_processed_files and ExperimentSet.experiments_in_set.other_processed_files. * * @param {ExperimentSet} context - JSON response from server for this endpoint/page depicting an ExperimentSet. * @returns {{ files: File[], title: string, type: string, description: string }[]} List of uniqued-by-title viewable collections. */ static combinedOtherProcessedFiles = memoize(function(context){ // Clone context let experiment_set = _.extend({}, context); // Add in Exp Bio & Tec Rep Nos, if available. if (Array.isArray(context.replicate_exps) && Array.isArray(context.experiments_in_set)) { experiment_set = combineExpsWithReplicateNumbersForExpSet(context); } // Clone -- so we don't modify props.context in place const collectionsFromExpSet = _.map(experiment_set.other_processed_files, function(collection){ const { files : origFiles } = collection; const files = _.map(origFiles || [], function(file){ return _.extend({ 'from_experiment_set' : experiment_set, 'from_experiment' : { 'from_experiment_set' : experiment_set, 'accession' : 'NONE' } }, file); }); return _.extend({}, collection, { files }); }); const collectionsFromExpSetTitles = _.pluck(collectionsFromExpSet, 'title'); // Files from collections from Experiments will be added to the arrays of files within these collections-from-expsets, w. new keys added if necessary. // We use foursight check to ensure titles are unique on back-end. const collectionsByTitle = _.object(_.zip(collectionsFromExpSetTitles, collectionsFromExpSet)); // Add 'from_experiment' info to each collection file so it gets put into right 'experiment' row in StackedTable. // Also required for SelectedFilesController const allCollectionsFromExperiments = _.reduce(experiment_set.experiments_in_set || [], function(memo, exp){ _.forEach(exp.other_processed_files || [], function(collection){ const { files : origFiles } = collection; const files = _.map(origFiles || [], function(file){ return _.extend({ 'from_experiment' : _.extend({ 'from_experiment_set' : experiment_set }, exp), 'from_experiment_set' : experiment_set }, file); }); memo.push(_.extend({}, collection, { files })); }); return memo; }, []); _.forEach(allCollectionsFromExperiments, function(collection){ const { title, files, description } = collection; if (collectionsByTitle[title]){ // Same title exists already from ExpSet.other_processed_files or another Experiment.other_processed_files. // Add in files unless is already present (== duplicate). _.forEach(files, function(f){ const duplicateExistingFile = _.find(collectionsByTitle[title].files, function(existFile){ return (object.itemUtil.atId(existFile) || 'a') === (object.itemUtil.atId(f) || 'b'); }); if (duplicateExistingFile){ logger.error('Found existing/duplicate file in ExperimentSet other_processed_files of Experiment File ' + f['@id']); // TODO send to analytics? } else { collectionsByTitle[title].files.push(f); } }); //clone description from exp's OPF if expset's OPF collection's missing collectionsByTitle[title].description = collectionsByTitle[title].description || description; } else { collectionsByTitle[title] = collection; } }); // Ensure have view permissions return _.filter(_.values(collectionsByTitle), SupplementaryFilesTabView.checkOPFCollectionPermission); }); static allReferenceFiles = memoize(function(context){ // We keep track of duplicates and add a "from_experiment.accessions" property if any to help mark/ID // it as being present on multiple experiments. // Alternatively we might have been able to set "from_experiment.accession" (no "s") to "NONE" but this // would imply that is attached to ExperimentSet and not Experiment for metadata.tsv stuff later down the road // and present issues. // Also changing "from_experiment" to an array is a bit more of a pain than ideal... const referenceFilesByAtID = new Map(); // We use map to ensure we keep order of first encounter. _.forEach(context.experiments_in_set || [], function(experiment){ _.forEach(experiment.reference_files || [], function(file){ // Add "from_experiment" and "from_experiment_set" to allow to be properly distributed in stacked block table. // Also for metadata TSV downloads. const fileAtID = object.itemUtil.atId(file); const existingFile = referenceFilesByAtID.get(fileAtID); if (existingFile){ if (!Array.isArray(existingFile.from_experiment.from_multiple_accessions)){ existingFile.from_experiment.from_multiple_accessions = [ existingFile.from_experiment.accession ]; } // We assume there's no duplicate reference files within a single experiment existingFile.from_experiment.from_multiple_accessions.push(experiment.accession); return; } else { // Add "from_experiment" and "from_experiment_set" to allow to be properly distributed in stacked block table. // Also for metadata TSV downloads. const extendedFile = _.extend({}, file, { 'from_experiment' : _.extend({}, experiment, { 'from_experiment_set' : context }), 'from_experiment_set' : context }); referenceFilesByAtID.set(fileAtID, extendedFile); } }); }); return [ ...referenceFilesByAtID.values() ]; }); render(){ const { context, session, width, mounted, windowWidth, href, selectedFiles } = this.props; const gridState = mounted && layout.responsiveGridState(windowWidth); const otherProcessedFileSetsCombined = SupplementaryFilesTabView.combinedOtherProcessedFiles(context); const otherProcessedFileSetsCombinedLen = otherProcessedFileSetsCombined.length; const referenceFiles = SupplementaryFilesTabView.allReferenceFiles(context); const referenceFilesLen = referenceFiles.length; const titleDetailString = ( (referenceFilesLen > 0 ? (referenceFilesLen + " Reference File" + (referenceFilesLen > 1 ? "s" : "")) : "") + (otherProcessedFileSetsCombinedLen > 0 && referenceFilesLen > 0 ? " and " : '') + (otherProcessedFileSetsCombinedLen > 0 ? (otherProcessedFileSetsCombinedLen + " Processed Files Collection" + (otherProcessedFileSetsCombinedLen > 1 ? "s" : "")) : '') ); const selectedFilesUniqueCount = SupplementaryFilesTabView.selectedFilesUniqueCount(selectedFiles); const commonProps = { context, width, mounted, windowWidth, href, ...SelectedFilesController.pick(this.props) }; const filenamePrefix = (context.accession || context.display_title) + "_supp_files_"; // TODO: Metadata.tsv stuff needs to be setup before we can select files from other_processed_files & reference_files //const commonProps = _.extend({ context, width, mounted, windowWidth }, SelectedFilesController.pick(this.props)); return ( <div className="processed-files-table-section"> <h3 className="tab-section-title"> Supplementary Files { titleDetailString.length > 0 ? <span className="small">&nbsp;&nbsp; &bull; {titleDetailString}</span> : null } {selectedFiles ? // Make sure data structure is present (even if empty) <div className="download-button-container pull-right" style={{ marginTop: -10 }}> <SelectedFilesDownloadButton {...{ selectedFiles, filenamePrefix, context, session }} disabled={selectedFilesUniqueCount === 0} id="expset-raw-files-download-files-btn" analyticsAddFilesToCart> <i className="icon icon-download fas icon-fw mr-07 align-baseline" /> <span className="d-none d-sm-inline">Download </span> <span className="count-to-download-integer">{selectedFilesUniqueCount}</span> <span className="d-none d-sm-inline text-400"> Supplementary Files</span> </SelectedFilesDownloadButton> </div> : null} </h3> <hr className="tab-section-title-horiz-divider"/> { referenceFilesLen > 0 ? <SupplementaryReferenceFilesSection {...commonProps} files={referenceFiles} /> : null } { _.map(otherProcessedFileSetsCombined, function(collection, index, all){ const defaultOpen = (gridState === 'sm' || gridState === 'xs' || !gridState) ? false : ((all.length < 4) || (index < 2)); return <SupplementaryFilesOPFCollection {..._.extend({ collection, index, defaultOpen }, commonProps)} key={index} />; }) } </div> ); } }
test/LabelSpec.js
laran/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Label from '../src/Label'; describe('Label', () => { it('Should output a label with message', () => { let instance = ReactTestUtils.renderIntoDocument( <Label> <strong>Message</strong> </Label> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong')); }); it('Should have bsClass by default', () => { let instance = ReactTestUtils.renderIntoDocument( <Label> Message </Label> ); assert.ok(React.findDOMNode(instance).className.match(/\blabel\b/)); }); it('Should have bsStyle by default', () => { let instance = ReactTestUtils.renderIntoDocument( <Label> Message </Label> ); assert.ok(React.findDOMNode(instance).className.match(/\blabel-default\b/)); }); });
examples/immutable/src/components/Hello.js
supasate/connected-react-router
import React from 'react' import HelloChild from './HelloChild' const Hello = () => ( <div> <div>Hello</div> <HelloChild /> </div> ) export default Hello
editor/components/IconButton.js
conundrumer/chroma-tone
/* eslint no-underscore-dangle: 0*/ 'use strict'; var React = require('react'); var MuiIconButton = require('material-ui').IconButton; var IconButton = React.createClass({ contextTypes: { muiTheme: React.PropTypes.object }, shouldComponentUpdate(nextProps, nextState) { let { style, tooltip, selected, disabled, transform } = this.props; let { style: style_, tooltip: tooltip_, selected: selected_, disabled: disabled_, transform: transform_ } = nextProps; return style !== style_ || tooltip !== tooltip_ || selected !== selected_ || disabled !== disabled_ || transform !== transform_; }, componentDidMount() { this.props.setRipple(this.startRipple, this.endRipple); }, // lol startRipple() { if (this.props.disabled) { return; } this.refs.iconButton.refs.button.refs.touchRipple.start(); }, endRipple() { if (this.props.disabled) { return; } this.refs.iconButton.refs.button.refs.touchRipple.end(); }, getColor() { let { primary1Color, // primary2Color, // primary3Color, textColor, disabledColor } = this.context.muiTheme.palette; return this.props.disabled ? disabledColor : (this.props.selected && (this.props.selectedColor || primary1Color) || textColor); }, render() { let { onTouchTap, onPress, onRelease, style, tooltip, disabled, transform, tooltipPosition } = this.props; let iconStyle = null; if (transform) { iconStyle = { transform: transform }; } let pressHandlers = { onMouseDown: onPress, onTouchStart: onPress, onMouseUp: onRelease, onMouseLeave: onRelease, onTouchEnd: onRelease, onTouchCancel: onRelease } return ( <MuiIconButton {...{ onTouchTap, style, tooltip, disabled, tooltipPosition }} {...pressHandlers} className='icon-button' ref='iconButton' iconStyle={iconStyle} > <this.props.children color={this.getColor()} disabled={this.props.disabled}/> </MuiIconButton> ); } }); module.exports = IconButton;
client/scripts/controllers/season1Ctrl.js
IHarryIJumper/trials-fusion-stats-cptsparkles
import React from 'react'; import { render } from 'react-dom'; import { SeasonOnePageComponent } from '../components/seasonsPages/season1Component.jsx'; export const renderSeason1Page = render(<SeasonOnePageComponent />, document.getElementById('season1-page-target'));
ajax/libs/react/0.14.8/react-dom.min.js
nolsherry/cdnjs
/** * ReactDOM v0.14.8 * * 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. * */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e(require("react"));else if("function"==typeof define&&define.amd)define(["react"],e);else{var f;f="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,f.ReactDOM=e(f.React)}}(function(e){return e.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED});
app/src/client/components/app/Home.js
dvdschwrtz/DockDev
import React from 'react'; var ReactTooltip = require("react-tooltip"); export default () => { return ( <div id="content"> </div> ); };
src/routes.js
codegaze/jekyll-admin
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import { ADMIN_PREFIX } from './constants'; import App from './containers/App'; import Configuration from './containers/views/Configuration'; import Pages from './containers/views/Pages'; import PageEdit from './containers/views/PageEdit'; import PageNew from './containers/views/PageNew'; import Documents from './containers/views/Documents'; import DocumentEdit from './containers/views/DocumentEdit'; import DocumentNew from './containers/views/DocumentNew'; import DataFiles from './containers/views/DataFiles'; import DataFileEdit from './containers/views/DataFileEdit'; import DataFileNew from './containers/views/DataFileNew'; import StaticFiles from './containers/views/StaticFiles'; import NotFound from './containers/views/NotFound'; export default ( <Route path={`${ADMIN_PREFIX}`} component={App}> <IndexRoute component={Pages}/> <Route path="configuration" component={Configuration} /> <Route path="pages" component={Pages} /> <Route path="pages/:id" component={PageEdit} /> <Route path="page/new" component={PageNew} /> <Route path="collections/:collection_name" component={Documents} /> <Route path="collections/:collection_name/:id" component={DocumentEdit} /> <Route path="collection/:collection_name/new" component={DocumentNew} /> // TODO check collection exists <Route path="datafiles" component={DataFiles} /> <Route path="datafiles/:data_file" component={DataFileEdit} /> <Route path="datafile/new" component={DataFileNew} /> <Route path="staticfiles" component={StaticFiles} /> <Route path={`${ADMIN_PREFIX}/*`} component={NotFound} /> </Route> );
example/misc.js
glenjamin/devboard
import React from 'react'; var BASE_URL = 'https://github.com/glenjamin/devboard/tree/master/example'; export function sourceLink(definecard, dir, file) { definecard( <a href={BASE_URL + '/' + dir + '/' + file} style={{ position: 'absolute', top: 5, right: 5 }} > Page Source </a> ); }
survey/static/lib/reactjs/react-with-addons.js
KevinSeghetti/survey
/** * React (with addons) v15.3.1 */ (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.React = 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){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutoFocusUtils */ 'use strict'; var ReactDOMComponentTree = _dereq_(46); var focusNode = _dereq_(172); var AutoFocusUtils = { focusDOMComponent: function () { focusNode(ReactDOMComponentTree.getNodeFromInstance(this)); } }; module.exports = AutoFocusUtils; },{"172":172,"46":46}],2:[function(_dereq_,module,exports){ /** * Copyright 2013-present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(20); var ExecutionEnvironment = _dereq_(164); var FallbackCompositionState = _dereq_(21); var SyntheticCompositionEvent = _dereq_(116); var SyntheticInputEvent = _dereq_(120); var keyOf = _dereq_(182); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({ onBeforeInput: null }), captured: keyOf({ onBeforeInputCapture: null }) }, dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste] }, compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionEnd: null }), captured: keyOf({ onCompositionEndCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionStart: null }), captured: keyOf({ onCompositionStartCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionUpdate: null }), captured: keyOf({ onCompositionUpdateCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; },{"116":116,"120":120,"16":16,"164":164,"182":182,"20":20,"21":21}],3:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridColumn: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],4:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations */ 'use strict'; var CSSProperty = _dereq_(3); var ExecutionEnvironment = _dereq_(164); var ReactInstrumentation = _dereq_(78); var camelizeStyleName = _dereq_(166); var dangerousStyleValue = _dereq_(134); var hyphenateStyleName = _dereq_(177); var memoizeStringOnly = _dereq_(183); var warning = _dereq_(187); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if ("development" !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; "development" !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0; }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; "development" !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0; }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; "development" !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0; }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; "development" !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0; }; var checkRenderMessage = function (owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; }; /** * @param {string} name * @param {*} value * @param {ReactDOMComponent} component */ var warnValidStyle = function (name, value, component) { var owner; if (component) { owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number' && isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function (styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if ("development" !== 'production') { warnValidStyle(styleName, styleValue, component); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue, component) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function (node, styles, component) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(component._debugID, 'update styles', styles); } var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if ("development" !== 'production') { warnValidStyle(styleName, styles[styleName], component); } var styleValue = dangerousStyleValue(styleName, styles[styleName], component); if (styleName === 'float' || styleName === 'cssFloat') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; },{"134":134,"164":164,"166":166,"177":177,"183":183,"187":187,"3":3,"78":78}],5:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var PooledClass = _dereq_(26); var invariant = _dereq_(178); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } _assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function (callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function () { var callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { !(callbacks.length === contexts.length) ? "development" !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, checkpoint: function () { return this._callbacks ? this._callbacks.length : 0; }, rollback: function (len) { if (this._callbacks) { this._callbacks.length = len; this._contexts.length = len; } }, /** * Resets the internal queue. * * @internal */ reset: function () { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function () { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; },{"153":153,"178":178,"188":188,"26":26}],6:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPropagators = _dereq_(20); var ExecutionEnvironment = _dereq_(164); var ReactDOMComponentTree = _dereq_(46); var ReactUpdates = _dereq_(107); var SyntheticEvent = _dereq_(118); var getEventTarget = _dereq_(142); var isEventSupported = _dereq_(149); var isTextInputElement = _dereq_(150); var keyOf = _dereq_(182); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({ onChange: null }), captured: keyOf({ onChangeCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange] } }; /** * For IE shims */ var activeElement = null; var activeElementInst = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementInst = null; } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topChange) { return targetInst; } } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(target, targetInst); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. // IE10+ fire input events to often, such when a placeholder // changes or when an input with a placeholder is focused. isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 11); } /** * (For IE <=11) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For IE <=11) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); if (activeElement.attachEvent) { activeElement.attachEvent('onpropertychange', handlePropertyChange); } else { activeElement.addEventListener('propertychange', handlePropertyChange, false); } } /** * (For IE <=11) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; if (activeElement.detachEvent) { activeElement.detachEvent('onpropertychange', handlePropertyChange); } else { activeElement.removeEventListener('propertychange', handlePropertyChange, false); } activeElement = null; activeElementInst = null; activeElementValue = null; activeElementValueProp = null; } /** * (For IE <=11) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetInstForInputEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return targetInst; } } function handleEventsForInputEventIE(topLevelType, target, targetInst) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9-11, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventIE(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementInst; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topClick) { return targetInst; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { if (doesChangeEventBubble) { getTargetInstFunc = getTargetInstForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputEvent; } else { getTargetInstFunc = getTargetInstForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } } }; module.exports = ChangeEventPlugin; },{"107":107,"118":118,"142":142,"149":149,"150":150,"16":16,"164":164,"17":17,"182":182,"20":20,"46":46}],7:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations */ 'use strict'; var DOMLazyTree = _dereq_(8); var Danger = _dereq_(12); var ReactMultiChildUpdateTypes = _dereq_(84); var ReactDOMComponentTree = _dereq_(46); var ReactInstrumentation = _dereq_(78); var createMicrosoftUnsafeLocalFunction = _dereq_(133); var setInnerHTML = _dereq_(155); var setTextContent = _dereq_(156); 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(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, 'replace text', stringText); } } var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup; if ("development" !== 'production') { dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) { Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup); if (prevInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation(prevInstance._debugID, 'replace with', markup.toString()); } else { var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node); if (nextInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation(nextInstance._debugID, 'mount', 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) { if ("development" !== 'production') { var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID; } for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'insert child', { toIndex: update.toIndex, content: update.content.toString() }); } break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'move child', { fromIndex: update.fromIndex, toIndex: update.toIndex }); } break; case ReactMultiChildUpdateTypes.SET_MARKUP: setInnerHTML(parentNode, update.content); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'replace children', update.content.toString()); } break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent(parentNode, update.content); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'replace text', update.content.toString()); } break; case ReactMultiChildUpdateTypes.REMOVE_NODE: removeChild(parentNode, update.fromNode); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(parentNodeDebugID, 'remove child', { fromIndex: update.fromIndex }); } break; } } } }; module.exports = DOMChildrenOperations; },{"12":12,"133":133,"155":155,"156":156,"46":46,"78":78,"8":8,"84":84}],8:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMLazyTree */ 'use strict'; var DOMNamespaces = _dereq_(9); var setInnerHTML = _dereq_(155); var createMicrosoftUnsafeLocalFunction = _dereq_(133); var setTextContent = _dereq_(156); var ELEMENT_NODE_TYPE = 1; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * 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(node, tree.html); } else if (tree.text != null) { setTextContent(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. 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_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.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(tree.node, html); } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent(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; module.exports = DOMLazyTree; },{"133":133,"155":155,"156":156,"9":9}],9:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMNamespaces */ 'use strict'; var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; module.exports = DOMNamespaces; },{}],10:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty */ 'use strict'; var _prodInvariant = _dereq_(153); var invariant = _dereq_(178); 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) ? "development" !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', 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) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0; if ("development" !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if ("development" !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; /* eslint-enable max-len */ /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\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 __DEV__. * @type {Object} */ getPossibleStandardName: "development" !== 'production' ? {} : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; },{"153":153,"178":178}],11:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations */ 'use strict'; var DOMProperty = _dereq_(10); var ReactDOMComponentTree = _dereq_(46); var ReactInstrumentation = _dereq_(78); var quoteAttributeValueForBrowser = _dereq_(152); var warning = _dereq_(187); var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; "development" !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function () { return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function (node) { node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, ''); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); 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.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); return; } if ("development" !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } if ("development" !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'update attribute', payload); } }, /** * Deletes an attributes from a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForAttribute: function (node, name) { node.removeAttribute(name); if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'remove attribute', name); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propertyInfo.hasBooleanValue) { node[propName] = false; } else { node[propName] = ''; } } else { node.removeAttribute(propertyInfo.attributeName); } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } if ("development" !== 'production') { ReactInstrumentation.debugTool.onHostOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, 'remove attribute', name); } } }; module.exports = DOMPropertyOperations; },{"10":10,"152":152,"187":187,"46":46,"78":78}],12:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger */ 'use strict'; var _prodInvariant = _dereq_(153); var DOMLazyTree = _dereq_(8); var ExecutionEnvironment = _dereq_(164); var createNodesFromMarkup = _dereq_(169); var emptyFunction = _dereq_(170); var invariant = _dereq_(178); 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.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('56') : void 0; !markup ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0; !(oldChild.nodeName !== 'HTML') ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : _prodInvariant('58') : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger; },{"153":153,"164":164,"169":169,"170":170,"178":178,"8":8}],13:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ 'use strict'; var keyOf = _dereq_(182); /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })]; module.exports = DefaultEventPluginOrder; },{"182":182}],14:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DisabledInputUtils */ 'use strict'; var disableableMouseListenerNames = { onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }; /** * Implements a host component that does not receive mouse events * when `disabled` is set. */ var DisabledInputUtils = { getHostProps: function (inst, props) { if (!props.disabled) { return props; } // Copy the props, except the mouse listeners var hostProps = {}; for (var key in props) { if (!disableableMouseListenerNames[key] && props.hasOwnProperty(key)) { hostProps[key] = props[key]; } } return hostProps; } }; module.exports = DisabledInputUtils; },{}],15:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(20); var ReactDOMComponentTree = _dereq_(46); var SyntheticMouseEvent = _dereq_(122); var keyOf = _dereq_(182); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { mouseEnter: { registrationName: keyOf({ onMouseEnter: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] }, mouseLeave: { registrationName: keyOf({ onMouseLeave: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] } }; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === topLevelTypes.topMouseOut) { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to); var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; module.exports = EnterLeaveEventPlugin; },{"122":122,"16":16,"182":182,"20":20,"46":46}],16:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ 'use strict'; var keyMirror = _dereq_(181); var PropagationPhases = keyMirror({ bubbled: null, captured: null }); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topAbort: null, topAnimationEnd: null, topAnimationIteration: null, topAnimationStart: null, topBlur: null, topCanPlay: null, topCanPlayThrough: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topDurationChange: null, topEmptied: null, topEncrypted: null, topEnded: null, topError: null, topFocus: null, topInput: null, topInvalid: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topLoadedData: null, topLoadedMetadata: null, topLoadStart: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topPause: null, topPlay: null, topPlaying: null, topProgress: null, topRateChange: null, topReset: null, topScroll: null, topSeeked: null, topSeeking: null, topSelectionChange: null, topStalled: null, topSubmit: null, topSuspend: null, topTextInput: null, topTimeUpdate: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topTransitionEnd: null, topVolumeChange: null, topWaiting: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"181":181}],17:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ 'use strict'; var _prodInvariant = _dereq_(153); var EventPluginRegistry = _dereq_(18); var EventPluginUtils = _dereq_(19); var ReactErrorUtils = _dereq_(68); var accumulateInto = _dereq_(129); var forEachAccumulated = _dereq_(138); var invariant = _dereq_(178); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; var getDictionaryKey = function (inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; }; /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {function} listener The callback to store. */ putListener: function (inst, registrationName, listener) { !(typeof listener === 'function') ? "development" !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0; var key = getDictionaryKey(inst); var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[key] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(inst, registrationName, listener); } }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; var key = getDictionaryKey(inst); return bankForRegistrationName && bankForRegistrationName[key]; }, /** * Deletes a listener from the registration bank. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { var key = getDictionaryKey(inst); delete bankForRegistrationName[key]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {object} inst The instance, which is the source of events. */ deleteAllListeners: function (inst) { var key = getDictionaryKey(inst); for (var registrationName in listenerBank) { if (!listenerBank.hasOwnProperty(registrationName)) { continue; } if (!listenerBank[registrationName][key]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][key]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? "development" !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; },{"129":129,"138":138,"153":153,"178":178,"18":18,"19":19,"68":68}],18:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry */ 'use strict'; var _prodInvariant = _dereq_(153); var invariant = _dereq_(178); /** * 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) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !PluginModule.extractEvents ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', 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) ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', 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 and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; if ("development" !== 'production') { 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 __DEV__. * @type {Object} */ possibleRegistrationNames: "development" !== 'production' ? {} : null, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (InjectedEventPluginOrder) { !!EventPluginOrder ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : 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] ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0; namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if ("development" !== 'production') { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } } }; module.exports = EventPluginRegistry; },{"153":153,"178":178}],19:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ 'use strict'; var _prodInvariant = _dereq_(153); var EventConstants = _dereq_(16); var ReactErrorUtils = _dereq_(68); var invariant = _dereq_(178); var warning = _dereq_(187); /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var TreeTraversal; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; if ("development" !== 'production') { "development" !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } }, injectTreeTraversal: function (Injected) { TreeTraversal = Injected; if ("development" !== 'production') { "development" !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0; } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if ("development" !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; "development" !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if ("development" !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if ("development" !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if ("development" !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? "development" !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, isAncestor: function (a, b) { return TreeTraversal.isAncestor(a, b); }, getLowestCommonAncestor: function (a, b) { return TreeTraversal.getLowestCommonAncestor(a, b); }, getParentInstance: function (inst) { return TreeTraversal.getParentInstance(inst); }, traverseTwoPhase: function (target, fn, arg) { return TreeTraversal.traverseTwoPhase(target, fn, arg); }, traverseEnterLeave: function (from, to, fn, argFrom, argTo) { return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo); }, injection: injection }; module.exports = EventPluginUtils; },{"153":153,"16":16,"178":178,"187":187,"68":68}],20:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ 'use strict'; var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPluginUtils = _dereq_(19); var accumulateInto = _dereq_(129); var forEachAccumulated = _dereq_(138); var warning = _dereq_(187); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, upwards, event) { if ("development" !== 'production') { "development" !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0; } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null; EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; },{"129":129,"138":138,"16":16,"17":17,"187":187,"19":19}],21:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FallbackCompositionState */ 'use strict'; var _assign = _dereq_(188); var PooledClass = _dereq_(26); var getTextContentAccessor = _dereq_(146); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } _assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; },{"146":146,"188":188,"26":26}],22:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ 'use strict'; var DOMProperty = _dereq_(10); var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, icon: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, 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, 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: {} }; module.exports = HTMLDOMPropertyConfig; },{"10":10}],23:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule KeyEscapeUtils * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {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 }; module.exports = KeyEscapeUtils; },{}],24:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedStateMixin */ 'use strict'; var ReactLink = _dereq_(80); var ReactStateSetters = _dereq_(101); /** * A simple mixin around ReactLink.forState(). * See https://facebook.github.io/react/docs/two-way-binding-helpers.html */ var LinkedStateMixin = { /** * Create a ReactLink that's linked to part of this component's state. The * ReactLink will have the current value of this.state[key] and will call * setState() when a change is requested. * * @param {string} key state key to update. Note: you may want to use keyOf() * if you're using Google Closure Compiler advanced mode. * @return {ReactLink} ReactLink instance linking to the state. */ linkState: function (key) { return new ReactLink(this.state[key], ReactStateSetters.createStateKeySetter(this, key)); } }; module.exports = LinkedStateMixin; },{"101":101,"80":80}],25:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactPropTypes = _dereq_(91); var ReactPropTypeLocations = _dereq_(90); var ReactPropTypesSecret = _dereq_(92); var invariant = _dereq_(178); var warning = _dereq_(187); 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) ? "development" !== '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) ? "development" !== '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) ? "development" !== '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); "development" !== '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; },{"153":153,"178":178,"187":187,"90":90,"91":91,"92":92}],26:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ 'use strict'; var _prodInvariant = _dereq_(153); var invariant = _dereq_(178); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? "development" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : 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) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; },{"153":153,"178":178}],27:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ 'use strict'; var _assign = _dereq_(188); var ReactChildren = _dereq_(32); var ReactComponent = _dereq_(35); var ReactPureComponent = _dereq_(93); var ReactClass = _dereq_(34); var ReactDOMFactories = _dereq_(49); var ReactElement = _dereq_(65); var ReactPropTypes = _dereq_(91); var ReactVersion = _dereq_(108); var onlyChild = _dereq_(151); var warning = _dereq_(187); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if ("development" !== 'production') { var ReactElementValidator = _dereq_(66); createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; if ("development" !== 'production') { var warned = false; __spread = function () { "development" !== 'production' ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.') : void 0; warned = true; return _assign.apply(null, arguments); }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, PureComponent: ReactPureComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; module.exports = React; },{"108":108,"151":151,"187":187,"188":188,"32":32,"34":34,"35":35,"49":49,"65":65,"66":66,"91":91,"93":93}],28:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter */ 'use strict'; var _assign = _dereq_(188); var EventConstants = _dereq_(16); var EventPluginRegistry = _dereq_(18); var ReactEventEmitterMixin = _dereq_(69); var ViewportMetrics = _dereq_(128); var getVendorPrefixedEventName = _dereq_(147); var isEventSupported = _dereq_(149); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var hasEventPageXY; var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend', topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration', topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * EventPluginHub.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when * pageX/pageY isn't supported (legacy browsers). * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (hasEventPageXY === undefined) { hasEventPageXY = document.createEvent && 'pageX' in document.createEvent('MouseEvent'); } if (!hasEventPageXY && !isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } } }); module.exports = ReactBrowserEventEmitter; },{"128":128,"147":147,"149":149,"16":16,"18":18,"188":188,"69":69}],29:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCSSTransitionGroup */ 'use strict'; var _assign = _dereq_(188); var React = _dereq_(27); var ReactTransitionGroup = _dereq_(105); var ReactCSSTransitionGroupChild = _dereq_(30); function createTransitionTimeoutPropValidator(transitionType) { var timeoutPropName = 'transition' + transitionType + 'Timeout'; var enabledPropName = 'transition' + transitionType; return function (props) { // If the transition is enabled if (props[enabledPropName]) { // If no timeout duration is provided if (props[timeoutPropName] == null) { return new Error(timeoutPropName + ' wasn\'t supplied to ReactCSSTransitionGroup: ' + 'this can cause unreliable animations and won\'t be supported in ' + 'a future version of React. See ' + 'https://fb.me/react-animation-transition-group-timeout for more ' + 'information.'); // If the duration isn't a number } else if (typeof props[timeoutPropName] !== 'number') { return new Error(timeoutPropName + ' must be a number (in milliseconds)'); } } }; } /** * An easy way to perform CSS transitions and animations when a React component * enters or leaves the DOM. * See https://facebook.github.io/react/docs/animation.html#high-level-api-reactcsstransitiongroup */ var ReactCSSTransitionGroup = React.createClass({ displayName: 'ReactCSSTransitionGroup', propTypes: { transitionName: ReactCSSTransitionGroupChild.propTypes.name, transitionAppear: React.PropTypes.bool, transitionEnter: React.PropTypes.bool, transitionLeave: React.PropTypes.bool, transitionAppearTimeout: createTransitionTimeoutPropValidator('Appear'), transitionEnterTimeout: createTransitionTimeoutPropValidator('Enter'), transitionLeaveTimeout: createTransitionTimeoutPropValidator('Leave') }, getDefaultProps: function () { return { transitionAppear: false, transitionEnter: true, transitionLeave: true }; }, _wrapChild: function (child) { // We need to provide this childFactory so that // ReactCSSTransitionGroupChild can receive updates to name, enter, and // leave while it is leaving. return React.createElement(ReactCSSTransitionGroupChild, { name: this.props.transitionName, appear: this.props.transitionAppear, enter: this.props.transitionEnter, leave: this.props.transitionLeave, appearTimeout: this.props.transitionAppearTimeout, enterTimeout: this.props.transitionEnterTimeout, leaveTimeout: this.props.transitionLeaveTimeout }, child); }, render: function () { return React.createElement(ReactTransitionGroup, _assign({}, this.props, { childFactory: this._wrapChild })); } }); module.exports = ReactCSSTransitionGroup; },{"105":105,"188":188,"27":27,"30":30}],30:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCSSTransitionGroupChild */ 'use strict'; var React = _dereq_(27); var ReactDOM = _dereq_(42); var CSSCore = _dereq_(162); var ReactTransitionEvents = _dereq_(104); var onlyChild = _dereq_(151); var TICK = 17; var ReactCSSTransitionGroupChild = React.createClass({ displayName: 'ReactCSSTransitionGroupChild', propTypes: { name: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.shape({ enter: React.PropTypes.string, leave: React.PropTypes.string, active: React.PropTypes.string }), React.PropTypes.shape({ enter: React.PropTypes.string, enterActive: React.PropTypes.string, leave: React.PropTypes.string, leaveActive: React.PropTypes.string, appear: React.PropTypes.string, appearActive: React.PropTypes.string })]).isRequired, // Once we require timeouts to be specified, we can remove the // boolean flags (appear etc.) and just accept a number // or a bool for the timeout flags (appearTimeout etc.) appear: React.PropTypes.bool, enter: React.PropTypes.bool, leave: React.PropTypes.bool, appearTimeout: React.PropTypes.number, enterTimeout: React.PropTypes.number, leaveTimeout: React.PropTypes.number }, transition: function (animationType, finishCallback, userSpecifiedDelay) { var node = ReactDOM.findDOMNode(this); if (!node) { if (finishCallback) { finishCallback(); } return; } var className = this.props.name[animationType] || this.props.name + '-' + animationType; var activeClassName = this.props.name[animationType + 'Active'] || className + '-active'; var timeout = null; var endListener = function (e) { if (e && e.target !== node) { return; } clearTimeout(timeout); CSSCore.removeClass(node, className); CSSCore.removeClass(node, activeClassName); ReactTransitionEvents.removeEndEventListener(node, endListener); // Usually this optional callback is used for informing an owner of // a leave animation and telling it to remove the child. if (finishCallback) { finishCallback(); } }; CSSCore.addClass(node, className); // Need to do this to actually trigger a transition. this.queueClassAndNode(activeClassName, node); // If the user specified a timeout delay. if (userSpecifiedDelay) { // Clean-up the animation after the specified delay timeout = setTimeout(endListener, userSpecifiedDelay); this.transitionTimeouts.push(timeout); } else { // DEPRECATED: this listener will be removed in a future version of react ReactTransitionEvents.addEndEventListener(node, endListener); } }, queueClassAndNode: function (className, node) { this.classNameAndNodeQueue.push({ className: className, node: node }); if (!this.timeout) { this.timeout = setTimeout(this.flushClassNameAndNodeQueue, TICK); } }, flushClassNameAndNodeQueue: function () { if (this.isMounted()) { this.classNameAndNodeQueue.forEach(function (obj) { CSSCore.addClass(obj.node, obj.className); }); } this.classNameAndNodeQueue.length = 0; this.timeout = null; }, componentWillMount: function () { this.classNameAndNodeQueue = []; this.transitionTimeouts = []; }, componentWillUnmount: function () { if (this.timeout) { clearTimeout(this.timeout); } this.transitionTimeouts.forEach(function (timeout) { clearTimeout(timeout); }); this.classNameAndNodeQueue.length = 0; }, componentWillAppear: function (done) { if (this.props.appear) { this.transition('appear', done, this.props.appearTimeout); } else { done(); } }, componentWillEnter: function (done) { if (this.props.enter) { this.transition('enter', done, this.props.enterTimeout); } else { done(); } }, componentWillLeave: function (done) { if (this.props.leave) { this.transition('leave', done, this.props.leaveTimeout); } else { done(); } }, render: function () { return onlyChild(this.props.children); } }); module.exports = ReactCSSTransitionGroupChild; },{"104":104,"151":151,"162":162,"27":27,"42":42}],31:[function(_dereq_,module,exports){ (function (process){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildReconciler */ 'use strict'; var ReactReconciler = _dereq_(95); var instantiateReactComponent = _dereq_(148); var KeyEscapeUtils = _dereq_(23); var shouldUpdateReactComponent = _dereq_(158); var traverseAllChildren = _dereq_(159); var warning = _dereq_(187); var ReactComponentTreeHook; 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 = _dereq_(38); } function instantiateChild(childInstances, child, name, selfDebugID) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if ("development" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = _dereq_(38); } if (!keyUnique) { "development" !== 'production' ? warning(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.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(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 = {}; if ("development" !== 'production') { traverseAllChildren(nestedChildNodes, function (childInsts, child, name) { return instantiateChild(childInsts, child, name, selfDebugID); }, childInstances); } else { traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); } return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, 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(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(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.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID); mountImages.push(nextChildMountImage); } } // 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.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren, safely) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild, safely); } } } }; module.exports = ReactChildReconciler; }).call(this,undefined) },{"148":148,"158":158,"159":159,"187":187,"23":23,"38":38,"95":95}],32:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ 'use strict'; var PooledClass = _dereq_(26); var ReactElement = _dereq_(65); var emptyFunction = _dereq_(170); var traverseAllChildren = _dereq_(159); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func; var context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result; var keyPrefix = bookKeeping.keyPrefix; var func = bookKeeping.func; var context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; },{"159":159,"170":170,"26":26,"65":65}],33:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildrenMutationWarningHook */ 'use strict'; var ReactComponentTreeHook = _dereq_(38); var warning = _dereq_(187); function handleElement(debugID, element) { if (element == null) { return; } if (element._shadowChildren === undefined) { return; } if (element._shadowChildren === element.props.children) { return; } var isMutated = false; if (Array.isArray(element._shadowChildren)) { if (element._shadowChildren.length === element.props.children.length) { for (var i = 0; i < element._shadowChildren.length; i++) { if (element._shadowChildren[i] !== element.props.children[i]) { isMutated = true; } } } else { isMutated = true; } } if (!Array.isArray(element._shadowChildren) || isMutated) { "development" !== 'production' ? warning(false, 'Component\'s children should not be mutated.%s', ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } } var ReactChildrenMutationWarningHook = { onMountComponent: function (debugID) { handleElement(debugID, ReactComponentTreeHook.getElement(debugID)); }, onUpdateComponent: function (debugID) { handleElement(debugID, ReactComponentTreeHook.getElement(debugID)); } }; module.exports = ReactChildrenMutationWarningHook; },{"187":187,"38":38}],34:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactClass */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var ReactComponent = _dereq_(35); var ReactElement = _dereq_(65); var ReactPropTypeLocations = _dereq_(90); var ReactPropTypeLocationNames = _dereq_(89); var ReactNoopUpdateQueue = _dereq_(86); var emptyObject = _dereq_(171); var invariant = _dereq_(178); var keyMirror = _dereq_(181); var keyOf = _dereq_(182); var warning = _dereq_(187); var MIXINS_KEY = keyOf({ mixins: null }); /** * Policies that describe methods in `ReactClassInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if ("development" !== 'production') { validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); } Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if ("development" !== 'production') { validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context); } Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if ("development" !== 'production') { validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; // noop function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but only in __DEV__ "development" !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0; } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.OVERRIDE_BASE) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.', name) : _prodInvariant('73', name) : void 0; } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('74', name) : void 0; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if ("development" !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; "development" !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0; } return; } !(typeof spec !== 'function') ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0; !!ReactElement.isValidElement(spec) ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0; var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? "development" !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if ("development" !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; !!isReserved ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.', name) : _prodInvariant('78', name) : void 0; var isInherited = name in Constructor; !!isInherited ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('79', name) : void 0; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : _prodInvariant('80') : void 0; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.', key) : _prodInvariant('81', key) : void 0; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if ("development" !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { "development" !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0; } else if (!args.length) { "development" !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback, 'replaceState'); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); } }; var ReactClassComponent = function () {}; _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { var Constructor = function (props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if ("development" !== 'production') { "development" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0; } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if ("development" !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (initialState === undefined && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : _prodInvariant('82', Constructor.displayName || 'ReactCompositeComponent') : void 0; this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if ("development" !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? "development" !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : _prodInvariant('83') : void 0; if ("development" !== 'production') { "development" !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : void 0; "development" !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; },{"153":153,"171":171,"178":178,"181":181,"182":182,"187":187,"188":188,"35":35,"65":65,"86":86,"89":89,"90":90}],35:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactNoopUpdateQueue = _dereq_(86); var canDefineProperty = _dereq_(131); var emptyObject = _dereq_(171); var invariant = _dereq_(178); var warning = _dereq_(187); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "development" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0; this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback, 'forceUpdate'); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if ("development" !== 'production') { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { "development" !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; },{"131":131,"153":153,"171":171,"178":178,"187":187,"86":86}],36:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ 'use strict'; var DOMChildrenOperations = _dereq_(7); var ReactDOMIDOperations = _dereq_(51); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup }; module.exports = ReactComponentBrowserEnvironment; },{"51":51,"7":7}],37:[function(_dereq_,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentEnvironment */ 'use strict'; var _prodInvariant = _dereq_(153); var invariant = _dereq_(178); 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 ? "development" !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : _prodInvariant('104') : void 0; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; },{"153":153,"178":178}],38:[function(_dereq_,module,exports){ /** * 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 ReactComponentTreeHook */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactCurrentOwner = _dereq_(41); var invariant = _dereq_(178); var warning = _dereq_(187); function isNative(fn) { // Based on isNative() from Lodash var funcToString = Function.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var reIsNative = RegExp('^' + funcToString // Take an example native function source for comparison .call(hasOwnProperty) // Strip regex characters so we can use it for regex .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') // Remove hasOwnProperty from the template to make it generic .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); try { var source = funcToString.call(fn); return reIsNative.test(source); } catch (err) { return false; } } var canUseCollections = // Array.from typeof Array.from === 'function' && // Map typeof Map === 'function' && isNative(Map) && // Map.prototype.keys Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) && // Set typeof Set === 'function' && isNative(Set) && // Set.prototype.keys Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys); var itemMap; var rootIDSet; var itemByKey; var rootByKey; if (canUseCollections) { itemMap = new Map(); rootIDSet = new Set(); } else { itemByKey = {}; rootByKey = {}; } var unmountedIDs = []; // Use non-numeric keys to prevent V8 performance issues: // https://github.com/facebook/react/pull/7232 function getKeyFromID(id) { return '.' + id; } function getIDFromKey(key) { return parseInt(key.substr(1), 10); } function get(id) { if (canUseCollections) { return itemMap.get(id); } else { var key = getKeyFromID(id); return itemByKey[key]; } } function remove(id) { if (canUseCollections) { itemMap['delete'](id); } else { var key = getKeyFromID(id); delete itemByKey[key]; } } function create(id, element, parentID) { var item = { element: element, parentID: parentID, text: null, childIDs: [], isMounted: false, updateCount: 0 }; if (canUseCollections) { itemMap.set(id, item); } else { var key = getKeyFromID(id); itemByKey[key] = item; } } function addRoot(id) { if (canUseCollections) { rootIDSet.add(id); } else { var key = getKeyFromID(id); rootByKey[key] = true; } } function removeRoot(id) { if (canUseCollections) { rootIDSet['delete'](id); } else { var key = getKeyFromID(id); delete rootByKey[key]; } } function getRegisteredIDs() { if (canUseCollections) { return Array.from(itemMap.keys()); } else { return Object.keys(itemByKey).map(getIDFromKey); } } function getRootIDs() { if (canUseCollections) { return Array.from(rootIDSet.keys()); } else { return Object.keys(rootByKey).map(getIDFromKey); } } function purgeDeep(id) { var item = get(id); if (item) { var childIDs = item.childIDs; remove(id); childIDs.forEach(purgeDeep); } } function describeComponentFrame(name, source, ownerName) { return '\n in ' + name + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); } function getDisplayName(element) { if (element == null) { return '#empty'; } else if (typeof element === 'string' || typeof element === 'number') { return '#text'; } else if (typeof element.type === 'string') { return element.type; } else { return element.type.displayName || element.type.name || 'Unknown'; } } function describeID(id) { var name = ReactComponentTreeHook.getDisplayName(id); var element = ReactComponentTreeHook.getElement(id); var ownerID = ReactComponentTreeHook.getOwnerID(id); var ownerName; if (ownerID) { ownerName = ReactComponentTreeHook.getDisplayName(ownerID); } "development" !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0; return describeComponentFrame(name, element && element._source, ownerName); } var ReactComponentTreeHook = { onSetChildren: function (id, nextChildIDs) { var item = get(id); item.childIDs = nextChildIDs; for (var i = 0; i < nextChildIDs.length; i++) { var nextChildID = nextChildIDs[i]; var nextChild = get(nextChildID); !nextChild ? "development" !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0; !(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? "development" !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0; !nextChild.isMounted ? "development" !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0; if (nextChild.parentID == null) { nextChild.parentID = id; // TODO: This shouldn't be necessary but mounting a new root during in // componentWillMount currently causes not-yet-mounted components to // be purged from our tree data so their parent ID is missing. } !(nextChild.parentID === id) ? "development" !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0; } }, onBeforeMountComponent: function (id, element, parentID) { create(id, element, parentID); }, onBeforeUpdateComponent: function (id, element) { var item = get(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.element = element; }, onMountComponent: function (id) { var item = get(id); item.isMounted = true; var isRoot = item.parentID === 0; if (isRoot) { addRoot(id); } }, onUpdateComponent: function (id) { var item = get(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.updateCount++; }, onUnmountComponent: function (id) { var item = get(id); if (item) { // We need to check if it exists. // `item` might not exist if it is inside an error boundary, and a sibling // error boundary child threw while mounting. Then this instance never // got a chance to mount, but it still gets an unmounting event during // the error boundary cleanup. item.isMounted = false; var isRoot = item.parentID === 0; if (isRoot) { removeRoot(id); } } unmountedIDs.push(id); }, purgeUnmountedComponents: function () { if (ReactComponentTreeHook._preventPurging) { // Should only be used for testing. return; } for (var i = 0; i < unmountedIDs.length; i++) { var id = unmountedIDs[i]; purgeDeep(id); } unmountedIDs.length = 0; }, isMounted: function (id) { var item = get(id); return item ? item.isMounted : false; }, getCurrentStackAddendum: function (topElement) { var info = ''; if (topElement) { var type = topElement.type; var name = typeof type === 'function' ? type.displayName || type.name : type; var owner = topElement._owner; info += describeComponentFrame(name || 'Unknown', topElement._source, owner && owner.getName()); } var currentOwner = ReactCurrentOwner.current; var id = currentOwner && currentOwner._debugID; info += ReactComponentTreeHook.getStackAddendumByID(id); return info; }, getStackAddendumByID: function (id) { var info = ''; while (id) { info += describeID(id); id = ReactComponentTreeHook.getParentID(id); } return info; }, getChildIDs: function (id) { var item = get(id); return item ? item.childIDs : []; }, getDisplayName: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element) { return null; } return getDisplayName(element); }, getElement: function (id) { var item = get(id); return item ? item.element : null; }, getOwnerID: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element || !element._owner) { return null; } return element._owner._debugID; }, getParentID: function (id) { var item = get(id); return item ? item.parentID : null; }, getSource: function (id) { var item = get(id); var element = item ? item.element : null; var source = element != null ? element._source : null; return source; }, getText: function (id) { var element = ReactComponentTreeHook.getElement(id); if (typeof element === 'string') { return element; } else if (typeof element === 'number') { return '' + element; } else { return null; } }, getUpdateCount: function (id) { var item = get(id); return item ? item.updateCount : 0; }, getRegisteredIDs: getRegisteredIDs, getRootIDs: getRootIDs }; module.exports = ReactComponentTreeHook; },{"153":153,"178":178,"187":187,"41":41}],39:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentWithPureRenderMixin */ 'use strict'; var shallowCompare = _dereq_(157); /** * If your React component's render function is "pure", e.g. it will render the * same result given the same props and state, provide this mixin for a * considerable performance boost. * * Most React components have pure render functions. * * Example: * * var ReactComponentWithPureRenderMixin = * require('ReactComponentWithPureRenderMixin'); * React.createClass({ * mixins: [ReactComponentWithPureRenderMixin], * * render: function() { * return <div className={this.props.className}>foo</div>; * } * }); * * Note: This only checks shallow equality for props and state. If these contain * complex data structures this mixin may have false-negatives for deeper * differences. Only mixin to components which have simple props and state, or * use `forceUpdate()` when you know deep data structures have changed. * * See https://facebook.github.io/react/docs/pure-render-mixin.html */ var ReactComponentWithPureRenderMixin = { shouldComponentUpdate: function (nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } }; module.exports = ReactComponentWithPureRenderMixin; },{"157":157}],40:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var ReactComponentEnvironment = _dereq_(37); var ReactCurrentOwner = _dereq_(41); var ReactElement = _dereq_(65); var ReactErrorUtils = _dereq_(68); var ReactInstanceMap = _dereq_(77); var ReactInstrumentation = _dereq_(78); var ReactNodeTypes = _dereq_(85); var ReactPropTypeLocations = _dereq_(90); var ReactReconciler = _dereq_(95); var checkReactTypeSpec = _dereq_(132); var emptyObject = _dereq_(171); var invariant = _dereq_(178); var shallowEqual = _dereq_(186); var shouldUpdateReactComponent = _dereq_(158); var warning = _dereq_(187); var CompositeTypes = { ImpureClass: 0, PureClass: 1, StatelessFunctional: 2 }; function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; var element = Component(this.props, this.context, this.updater); warnIfInvalidElement(Component, element); return element; }; function warnIfInvalidElement(Component, element) { if ("development" !== 'production') { "development" !== 'production' ? warning(element === null || element === false || ReactElement.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0; "development" !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0; } } function invokeComponentDidMountWithTimer() { var publicInstance = this._instance; if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidMount'); } publicInstance.componentDidMount(); if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidMount'); } } function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) { var publicInstance = this._instance; if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentDidUpdate'); } publicInstance.componentDidUpdate(prevProps, prevState, prevContext); if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentDidUpdate'); } } function shouldConstruct(Component) { return !!(Component.prototype && Component.prototype.isReactComponent); } function isPureComponent(Component) { return !!(Component.prototype && Component.prototype.isPureReactComponent); } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = 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; if ("development" !== 'production') { 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) { 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; warnIfInvalidElement(Component, renderedElement); !(inst === null || inst === false || ReactElement.isValidElement(inst)) ? "development" !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0; inst = new StatelessComponent(Component); this._compositeType = CompositeTypes.StatelessFunctional; } else { if (isPureComponent(Component)) { this._compositeType = CompositeTypes.PureClass; } else { this._compositeType = CompositeTypes.ImpureClass; } } if ("development" !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { "development" !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0; } var propsMutated = inst.props !== publicProps; var componentName = Component.displayName || Component.name || 'Component'; "development" !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0; } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = updateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if ("development" !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. "development" !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0; "development" !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : void 0; "development" !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0; "development" !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; 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) { if ("development" !== 'production') { transaction.getReactMountReady().enqueue(invokeComponentDidMountWithTimer, this); } else { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } } return markup; }, _constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) { if ("development" !== 'production') { ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } finally { ReactCurrentOwner.current = null; } } else { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } }, _constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) { var Component = this._currentElement.type; var instanceOrElement; if (doConstruct) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'ctor'); } } instanceOrElement = new Component(publicProps, publicContext, updateQueue); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'ctor'); } } } else { // 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. if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render'); } } instanceOrElement = Component(publicProps, publicContext, updateQueue); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render'); } } } return instanceOrElement; }, performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var markup; var checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } catch (e) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onError(); } } // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); this._renderedComponent.unmountComponent(true); transaction.rollback(checkpoint); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } return markup; }, performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var inst = this._instance; if (inst.componentWillMount) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillMount'); } } inst.componentWillMount(); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(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); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } var nodeType = ReactNodeTypes.getType(renderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var selfDebugID = 0; if ("development" !== 'production') { selfDebugID = this._debugID; } var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), selfDebugID); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(this._debugID, child._debugID !== 0 ? [child._debugID] : []); } } return markup; }, getHostNode: function () { return ReactReconciler.getHostNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (safely) { if (!this._renderedComponent) { return; } var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { inst._calledComponentWillUnmount = true; if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUnmount'); } } if (safely) { var name = this.getName() + '.componentWillUnmount()'; ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst)); } else { inst.componentWillUnmount(); } if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUnmount'); } } } if (this._renderedComponent) { ReactReconciler.unmountComponent(this._renderedComponent, safely); this._renderedNodeType = null; this._renderedComponent = null; this._instance = null; } // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = 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.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if ("development" !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkContextTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; if ("development" !== 'production') { ReactInstrumentation.debugTool.onBeginProcessingChildContext(); } var childContext = inst.getChildContext && inst.getChildContext(); if ("development" !== 'production') { ReactInstrumentation.debugTool.onEndProcessingChildContext(); } if (childContext) { !(typeof Component.childContextTypes === 'object') ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0; if ("development" !== 'production') { this._checkContextTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); } for (var name in childContext) { !(name in Component.childContextTypes) ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0; } return _assign({}, currentContext, childContext); } 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) { checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID); }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { 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) ? "development" !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', 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) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillReceiveProps'); } } inst.componentWillReceiveProps(nextProps, nextContext); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillReceiveProps'); } } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = true; if (!this._pendingForceUpdate) { if (inst.shouldComponentUpdate) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'shouldComponentUpdate'); } } shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'shouldComponentUpdate'); } } } else { if (this._compositeType === CompositeTypes.PureClass) { shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState); } } } if ("development" !== 'production') { "development" !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0; } 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; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = _assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; _assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'componentWillUpdate'); } } inst.componentWillUpdate(nextProps, nextState, nextContext); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'componentWillUpdate'); } } } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { if ("development" !== 'production') { transaction.getReactMountReady().enqueue(invokeComponentDidUpdateWithTimer.bind(this, prevProps, prevState, prevContext), this); } else { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance); ReactReconciler.unmountComponent(prevComponentInstance, false); var nodeType = ReactNodeTypes.getType(nextRenderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var selfDebugID = 0; if ("development" !== 'production') { selfDebugID = this._debugID; } var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), selfDebugID); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(this._debugID, child._debugID !== 0 ? [child._debugID] : []); } } this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) { ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, 'render'); } } var renderedComponent = inst.render(); if ("development" !== 'production') { if (this._debugID !== 0) { ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, 'render'); } } if ("development" !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (renderedComponent === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: function () { var renderedComponent; if ("development" !== 'production' || this._compositeType !== CompositeTypes.StatelessFunctional) { ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } } else { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } !( // TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? "development" !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0; return renderedComponent; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? "development" !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : _prodInvariant('110') : void 0; var publicComponentInstance = component.getPublicInstance(); if ("development" !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; "development" !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (this._compositeType === CompositeTypes.StatelessFunctional) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; var ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; },{"132":132,"153":153,"158":158,"171":171,"178":178,"186":186,"187":187,"188":188,"37":37,"41":41,"65":65,"68":68,"77":77,"78":78,"85":85,"90":90,"95":95}],41:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],42:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactDOMComponentTree = _dereq_(46); var ReactDefaultInjection = _dereq_(64); var ReactMount = _dereq_(82); var ReactReconciler = _dereq_(95); var ReactUpdates = _dereq_(107); var ReactVersion = _dereq_(108); var findDOMNode = _dereq_(136); var getHostComponentFromComposite = _dereq_(143); var renderSubtreeIntoContainer = _dereq_(154); var warning = _dereq_(187); ReactDefaultInjection.inject(); var ReactDOM = { findDOMNode: findDOMNode, render: ReactMount.render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. /* eslint-enable camelcase */ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ ComponentTree: { getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode, getNodeFromInstance: function (inst) { // inst is an internal instance (but could be a composite) if (inst._renderedComponent) { inst = getHostComponentFromComposite(inst); } if (inst) { return ReactDOMComponentTree.getNodeFromInstance(inst); } else { return null; } } }, Mount: ReactMount, Reconciler: ReactReconciler }); } if ("development" !== 'production') { var ExecutionEnvironment = _dereq_(164); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { // Firefox does not have the issue with devtools loaded over file:// var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1; console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools'); } } var testFunc = function testFn() {}; "development" !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0; // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; "development" !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : void 0; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { "development" !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0; break; } } } } if ("development" !== 'production') { var ReactInstrumentation = _dereq_(78); var ReactDOMUnknownPropertyHook = _dereq_(61); var ReactDOMNullInputValuePropHook = _dereq_(53); ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook); ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook); } module.exports = ReactDOM; },{"107":107,"108":108,"136":136,"143":143,"154":154,"164":164,"187":187,"46":46,"53":53,"61":61,"64":64,"78":78,"82":82,"95":95}],43:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ 'use strict'; var DisabledInputUtils = _dereq_(14); /** * Implements a <button> host component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = { getHostProps: DisabledInputUtils.getHostProps }; module.exports = ReactDOMButton; },{"14":14}],44:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent */ /* global hasOwnProperty:true */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var AutoFocusUtils = _dereq_(1); var CSSPropertyOperations = _dereq_(4); var DOMLazyTree = _dereq_(8); var DOMNamespaces = _dereq_(9); var DOMProperty = _dereq_(10); var DOMPropertyOperations = _dereq_(11); var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPluginRegistry = _dereq_(18); var ReactBrowserEventEmitter = _dereq_(28); var ReactDOMButton = _dereq_(43); var ReactDOMComponentFlags = _dereq_(45); var ReactDOMComponentTree = _dereq_(46); var ReactDOMInput = _dereq_(52); var ReactDOMOption = _dereq_(54); var ReactDOMSelect = _dereq_(55); var ReactDOMTextarea = _dereq_(59); var ReactInstrumentation = _dereq_(78); var ReactMultiChild = _dereq_(83); var ReactServerRenderingTransaction = _dereq_(99); var emptyFunction = _dereq_(170); var escapeTextContentForBrowser = _dereq_(135); var invariant = _dereq_(178); var isEventSupported = _dereq_(149); var keyOf = _dereq_(182); var shallowEqual = _dereq_(186); var validateDOMNesting = _dereq_(161); var warning = _dereq_(187); var Flags = ReactDOMComponentFlags; var deleteListener = EventPluginHub.deleteListener; var getNode = ReactDOMComponentTree.getNodeFromInstance; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = EventPluginRegistry.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var STYLE = keyOf({ style: null }); var HTML = keyOf({ __html: null }); var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; // Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE). var DOC_FRAGMENT_TYPE = 11; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined because undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; "development" !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : void 0; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[component._tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : _prodInvariant('137', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? "development" !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : _prodInvariant('60') : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? "development" !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : _prodInvariant('61') : void 0; } if ("development" !== 'production') { "development" !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0; "development" !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : void 0; "development" !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0; } !(props.style == null || typeof props.style === 'object') ? "development" !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(component)) : _prodInvariant('62', getDeclarationErrorAddendum(component)) : void 0; } function enqueuePutListener(inst, registrationName, listener, transaction) { if (transaction instanceof ReactServerRenderingTransaction) { return; } if ("development" !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. "development" !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0; } var containerInfo = inst._hostContainerInfo; var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE; var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; listenTo(registrationName, doc); transaction.getReactMountReady().enqueue(putListener, { inst: inst, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener); } function inputPostMount() { var inst = this; ReactDOMInput.postMountWrapper(inst); } function textareaPostMount() { var inst = this; ReactDOMTextarea.postMountWrapper(inst); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } var setContentChildForInstrumentation = emptyFunction; if ("development" !== 'production') { setContentChildForInstrumentation = 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; } 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 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 ? "development" !== 'production' ? invariant(false, 'Must be mounted to trap events') : _prodInvariant('63') : void 0; var node = getNode(inst); !node ? "development" !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : _prodInvariant('64') : void 0; switch (inst._tag) { case 'iframe': case 'object': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); } } break; case 'source': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node)]; break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)]; break; case 'input': case 'select': case 'textarea': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topInvalid, 'invalid', node)]; break; } } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; // NOTE: menuitem's close tag should be omitted, but that causes problems. var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = _assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? "development" !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : _prodInvariant('65', 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; validateDangerousTag(tag); this._currentElement = element; this._tag = tag.toLowerCase(); this._namespaceURI = null; this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._hostNode = null; this._hostParent = null; this._rootNodeID = 0; this._domID = 0; this._hostContainerInfo = null; this._wrapperState = null; this._topLevelWrapper = null; this._flags = 0; if ("development" !== 'production') { this._ancestorInfo = null; setContentChildForInstrumentation.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 'link': case 'object': case 'source': case 'video': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'button': props = ReactDOMButton.getHostProps(this, props, hostParent); break; case 'input': ReactDOMInput.mountWrapper(this, props, hostParent); props = ReactDOMInput.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'option': ReactDOMOption.mountWrapper(this, props, hostParent); props = ReactDOMOption.getHostProps(this, props); break; case 'select': ReactDOMSelect.mountWrapper(this, props, hostParent); props = ReactDOMSelect.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, hostParent); props = ReactDOMTextarea.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; } assertValidProps(this, props); // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI; var parentTag; if (hostParent != null) { namespaceURI = hostParent._namespaceURI; parentTag = hostParent._tag; } else if (hostContainerInfo._tag) { namespaceURI = hostContainerInfo._namespaceURI; parentTag = hostContainerInfo._tag; } if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') { namespaceURI = DOMNamespaces.html; } if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'svg') { namespaceURI = DOMNamespaces.svg; } else if (this._tag === 'math') { namespaceURI = DOMNamespaces.mathml; } } this._namespaceURI = namespaceURI; if ("development" !== 'production') { 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(this._tag, this, parentInfo); } this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var el; if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); var type = this._currentElement.type; div.innerHTML = '<' + type + '></' + type + '>'; el = div.removeChild(div.firstChild); } else if (props.is) { el = ownerDocument.createElement(this._currentElement.type, props.is); } else { // Separate else branch instead of using `props.is || undefined` above becuase 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(this._currentElement.type); } } else { el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type); } ReactDOMComponentTree.precacheNode(this, el); this._flags |= Flags.hasCachedChildNodes; if (!this._hostParent) { DOMPropertyOperations.setAttributeForRoot(el); } this._updateDOMProperties(null, props, transaction); var lazyTree = DOMLazyTree(el); this._createInitialChildren(transaction, props, context, lazyTree); mountImage = lazyTree; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(inputPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'textarea': transaction.getReactMountReady().enqueue(textareaPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'select': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'button': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'option': transaction.getReactMountReady().enqueue(optionPostMount, 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) { enqueuePutListener(this, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if ("development" !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = _assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._hostParent) { ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID); return ret; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); if ("development" !== 'production') { setContentChildForInstrumentation.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) { if (innerHTML.__html != null) { DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node if ("development" !== 'production') { setContentChildForInstrumentation.call(this, contentToUse); } DOMLazyTree.queueText(lazyTree, contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { DOMLazyTree.queueChild(lazyTree, mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'button': lastProps = ReactDOMButton.getHostProps(this, lastProps); nextProps = ReactDOMButton.getHostProps(this, nextProps); break; case 'input': lastProps = ReactDOMInput.getHostProps(this, lastProps); nextProps = ReactDOMInput.getHostProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getHostProps(this, lastProps); nextProps = ReactDOMOption.getHostProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getHostProps(this, lastProps); nextProps = ReactDOMSelect.getHostProps(this, nextProps); break; case 'textarea': lastProps = ReactDOMTextarea.getHostProps(this, lastProps); nextProps = ReactDOMTextarea.getHostProps(this, nextProps); break; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction); 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.updateWrapper(this); break; case 'textarea': ReactDOMTextarea.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) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, lastProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { if (nextProp) { if ("development" !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = _assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); if ("development" !== 'production') { setContentChildForInstrumentation.call(this, nextContent); } } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } else if (nextChildren != null) { if ("development" !== 'production') { setContentChildForInstrumentation.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) { switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': 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 '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. */ !false ? "development" !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.', this._tag) : _prodInvariant('66', this._tag) : void 0; break; } this.unmountChildren(safely); ReactDOMComponentTree.uncacheNode(this); EventPluginHub.deleteAllListeners(this); this._rootNodeID = 0; this._domID = 0; this._wrapperState = null; if ("development" !== 'production') { setContentChildForInstrumentation.call(this, null); } }, getPublicInstance: function () { return getNode(this); } }; _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; },{"1":1,"10":10,"11":11,"135":135,"149":149,"153":153,"16":16,"161":161,"17":17,"170":170,"178":178,"18":18,"182":182,"186":186,"187":187,"188":188,"28":28,"4":4,"43":43,"45":45,"46":46,"52":52,"54":54,"55":55,"59":59,"78":78,"8":8,"83":83,"9":9,"99":99}],45:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponentFlags */ 'use strict'; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; module.exports = ReactDOMComponentFlags; },{}],46:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponentTree */ 'use strict'; var _prodInvariant = _dereq_(153); var DOMProperty = _dereq_(10); var ReactDOMComponentFlags = _dereq_(45); var invariant = _dereq_(178); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags; var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2); /** * Drill down (through composites and empty components) until we get a 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 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 (childNode.nodeType === 1 && childNode.getAttribute(ATTR_NAME) === String(childID) || childNode.nodeType === 8 && childNode.nodeValue === ' react-text: ' + childID + ' ' || childNode.nodeType === 8 && childNode.nodeValue === ' react-empty: ' + childID + ' ') { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. !false ? "development" !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0; } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = getClosestInstanceFromNode(node); if (inst != null && inst._hostNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._hostNode !== undefined) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : 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 ? "development" !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : 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; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode }; module.exports = ReactDOMComponentTree; },{"10":10,"153":153,"178":178,"45":45}],47:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMContainerInfo */ 'use strict'; var validateDOMNesting = _dereq_(161); var DOC_NODE_TYPE = 9; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; if ("development" !== 'production') { info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null; } return info; } module.exports = ReactDOMContainerInfo; },{"161":161}],48:[function(_dereq_,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMEmptyComponent */ 'use strict'; var _assign = _dereq_(188); var DOMLazyTree = _dereq_(8); var ReactDOMComponentTree = _dereq_(46); 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; }; _assign(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.precacheNode(this, node); return DOMLazyTree(node); } else { if (transaction.renderToStaticMarkup) { // Normally we'd insert a comment node, but since this is a situation // where React won't take over (static pages), we can simply return // nothing. return ''; } return '<!--' + nodeValue + '-->'; } }, receiveComponent: function () {}, getHostNode: function () { return ReactDOMComponentTree.getNodeFromInstance(this); }, unmountComponent: function () { ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMEmptyComponent; },{"188":188,"46":46,"8":8}],49:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFactories */ 'use strict'; var ReactElement = _dereq_(65); /** * Create a factory that creates HTML tag elements. * * @private */ var createDOMFactory = ReactElement.createFactory; if ("development" !== 'production') { var ReactElementValidator = _dereq_(66); createDOMFactory = ReactElementValidator.createFactory; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = { a: createDOMFactory('a'), abbr: createDOMFactory('abbr'), address: createDOMFactory('address'), area: createDOMFactory('area'), article: createDOMFactory('article'), aside: createDOMFactory('aside'), audio: createDOMFactory('audio'), b: createDOMFactory('b'), base: createDOMFactory('base'), bdi: createDOMFactory('bdi'), bdo: createDOMFactory('bdo'), big: createDOMFactory('big'), blockquote: createDOMFactory('blockquote'), body: createDOMFactory('body'), br: createDOMFactory('br'), button: createDOMFactory('button'), canvas: createDOMFactory('canvas'), caption: createDOMFactory('caption'), cite: createDOMFactory('cite'), code: createDOMFactory('code'), col: createDOMFactory('col'), colgroup: createDOMFactory('colgroup'), data: createDOMFactory('data'), datalist: createDOMFactory('datalist'), dd: createDOMFactory('dd'), del: createDOMFactory('del'), details: createDOMFactory('details'), dfn: createDOMFactory('dfn'), dialog: createDOMFactory('dialog'), div: createDOMFactory('div'), dl: createDOMFactory('dl'), dt: createDOMFactory('dt'), em: createDOMFactory('em'), embed: createDOMFactory('embed'), fieldset: createDOMFactory('fieldset'), figcaption: createDOMFactory('figcaption'), figure: createDOMFactory('figure'), footer: createDOMFactory('footer'), form: createDOMFactory('form'), h1: createDOMFactory('h1'), h2: createDOMFactory('h2'), h3: createDOMFactory('h3'), h4: createDOMFactory('h4'), h5: createDOMFactory('h5'), h6: createDOMFactory('h6'), head: createDOMFactory('head'), header: createDOMFactory('header'), hgroup: createDOMFactory('hgroup'), hr: createDOMFactory('hr'), html: createDOMFactory('html'), i: createDOMFactory('i'), iframe: createDOMFactory('iframe'), img: createDOMFactory('img'), input: createDOMFactory('input'), ins: createDOMFactory('ins'), kbd: createDOMFactory('kbd'), keygen: createDOMFactory('keygen'), label: createDOMFactory('label'), legend: createDOMFactory('legend'), li: createDOMFactory('li'), link: createDOMFactory('link'), main: createDOMFactory('main'), map: createDOMFactory('map'), mark: createDOMFactory('mark'), menu: createDOMFactory('menu'), menuitem: createDOMFactory('menuitem'), meta: createDOMFactory('meta'), meter: createDOMFactory('meter'), nav: createDOMFactory('nav'), noscript: createDOMFactory('noscript'), object: createDOMFactory('object'), ol: createDOMFactory('ol'), optgroup: createDOMFactory('optgroup'), option: createDOMFactory('option'), output: createDOMFactory('output'), p: createDOMFactory('p'), param: createDOMFactory('param'), picture: createDOMFactory('picture'), pre: createDOMFactory('pre'), progress: createDOMFactory('progress'), q: createDOMFactory('q'), rp: createDOMFactory('rp'), rt: createDOMFactory('rt'), ruby: createDOMFactory('ruby'), s: createDOMFactory('s'), samp: createDOMFactory('samp'), script: createDOMFactory('script'), section: createDOMFactory('section'), select: createDOMFactory('select'), small: createDOMFactory('small'), source: createDOMFactory('source'), span: createDOMFactory('span'), strong: createDOMFactory('strong'), style: createDOMFactory('style'), sub: createDOMFactory('sub'), summary: createDOMFactory('summary'), sup: createDOMFactory('sup'), table: createDOMFactory('table'), tbody: createDOMFactory('tbody'), td: createDOMFactory('td'), textarea: createDOMFactory('textarea'), tfoot: createDOMFactory('tfoot'), th: createDOMFactory('th'), thead: createDOMFactory('thead'), time: createDOMFactory('time'), title: createDOMFactory('title'), tr: createDOMFactory('tr'), track: createDOMFactory('track'), u: createDOMFactory('u'), ul: createDOMFactory('ul'), 'var': createDOMFactory('var'), video: createDOMFactory('video'), wbr: createDOMFactory('wbr'), // SVG circle: createDOMFactory('circle'), clipPath: createDOMFactory('clipPath'), defs: createDOMFactory('defs'), ellipse: createDOMFactory('ellipse'), g: createDOMFactory('g'), image: createDOMFactory('image'), line: createDOMFactory('line'), linearGradient: createDOMFactory('linearGradient'), mask: createDOMFactory('mask'), path: createDOMFactory('path'), pattern: createDOMFactory('pattern'), polygon: createDOMFactory('polygon'), polyline: createDOMFactory('polyline'), radialGradient: createDOMFactory('radialGradient'), rect: createDOMFactory('rect'), stop: createDOMFactory('stop'), svg: createDOMFactory('svg'), text: createDOMFactory('text'), tspan: createDOMFactory('tspan') }; module.exports = ReactDOMFactories; },{"65":65,"66":66}],50:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFeatureFlags */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: true }; module.exports = ReactDOMFeatureFlags; },{}],51:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations */ 'use strict'; var DOMChildrenOperations = _dereq_(7); var ReactDOMComponentTree = _dereq_(46); /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); } }; module.exports = ReactDOMIDOperations; },{"46":46,"7":7}],52:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var DisabledInputUtils = _dereq_(14); var DOMPropertyOperations = _dereq_(11); var LinkedValueUtils = _dereq_(25); var ReactDOMComponentTree = _dereq_(46); var ReactUpdates = _dereq_(107); var invariant = _dereq_(178); var warning = _dereq_(187); var didWarnValueLink = false; var didWarnCheckedLink = false; var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } function isControlled(props) { var usesChecked = props.type === 'checkbox' || props.type === 'radio'; return usesChecked ? props.checked !== undefined : props.value !== undefined; } /** * 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 = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var hostProps = _assign({ // 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 }, DisabledInputUtils.getHostProps(inst, props), { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if ("development" !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); var owner = inst._currentElement._owner; if (props.valueLink !== undefined && !didWarnValueLink) { "development" !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.checkedLink !== undefined && !didWarnCheckedLink) { "development" !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnCheckedLink = true; } if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { "development" !== 'production' ? warning(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) : void 0; didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { "development" !== 'production' ? warning(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) : void 0; 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, onChange: _handleChange.bind(inst) }; if ("development" !== 'production') { inst._wrapperState.controlled = isControlled(props); } }, updateWrapper: function (inst) { var props = inst._currentElement.props; if ("development" !== 'production') { var controlled = isControlled(props); var owner = inst._currentElement._owner; if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { "development" !== 'production' ? warning(false, '%s 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', owner && owner.getName() || 'A component', props.type) : void 0; didWarnUncontrolledToControlled = true; } if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { "development" !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnControlledToUncontrolled = true; } } // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false); } var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } } else { if (props.value == null && props.defaultValue != null) { 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.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; } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactDOMComponentTree.getNodeFromInstance(this); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode); !otherInstance ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : _prodInvariant('90') : void 0; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; },{"107":107,"11":11,"14":14,"153":153,"178":178,"187":187,"188":188,"25":25,"46":46}],53:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMNullInputValuePropHook */ 'use strict'; var ReactComponentTreeHook = _dereq_(38); var warning = _dereq_(187); var didWarnValueNull = false; function handleElement(debugID, element) { if (element == null) { return; } if (element.type !== 'input' && element.type !== 'textarea' && element.type !== 'select') { return; } if (element.props != null && element.props.value === null && !didWarnValueNull) { "development" !== 'production' ? warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; didWarnValueNull = true; } } var ReactDOMNullInputValuePropHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMNullInputValuePropHook; },{"187":187,"38":38}],54:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ 'use strict'; var _assign = _dereq_(188); var ReactChildren = _dereq_(32); var ReactDOMComponentTree = _dereq_(46); var ReactDOMSelect = _dereq_(55); var warning = _dereq_(187); var didWarnInvalidOptionChildren = false; function flattenChildren(children) { var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. ReactChildren.forEach(children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; "development" !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0; } }); 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>. if ("development" !== 'production') { "development" !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0; } // Look up whether this option is 'selected' var selectValue = null; if (hostParent != null) { var selectParent = hostParent; if (selectParent._tag === 'optgroup') { selectParent = selectParent._hostParent; } if (selectParent != null && selectParent._tag === 'select') { selectValue = ReactDOMSelect.getSelectValueContext(selectParent); } } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { 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.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getHostProps: function (inst, props) { var hostProps = _assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { hostProps.selected = inst._wrapperState.selected; } var content = flattenChildren(props.children); if (content) { hostProps.children = content; } return hostProps; } }; module.exports = ReactDOMOption; },{"187":187,"188":188,"32":32,"46":46,"55":55}],55:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ 'use strict'; var _assign = _dereq_(188); var DisabledInputUtils = _dereq_(14); var LinkedValueUtils = _dereq_(25); var ReactDOMComponentTree = _dereq_(46); var ReactUpdates = _dereq_(107); var warning = _dereq_(187); var didWarnValueLink = false; var didWarnValueDefaultValue = false; function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); if (props.valueLink !== undefined && !didWarnValueLink) { "development" !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { "development" !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } else if (!props.multiple && isArray) { "development" !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactDOMComponentTree.getNodeFromInstance(inst).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> 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 _assign({}, DisabledInputUtils.getHostProps(inst, props), { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if ("development" !== 'production') { checkSelectPropTypes(inst, props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, listeners: null, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { "development" !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValueDefaultValue = true; } }, getSelectValueContext: function (inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); if (this._rootNodeID) { this._wrapperState.pendingUpdate = true; } ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; },{"107":107,"14":14,"187":187,"188":188,"25":25,"46":46}],56:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ 'use strict'; var ExecutionEnvironment = _dereq_(164); var getNodeForCharacterOffset = _dereq_(145); var getTextContentAccessor = _dereq_(146); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (offsets.end === undefined) { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; },{"145":145,"146":146,"164":164}],57:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMServer */ 'use strict'; var ReactDefaultInjection = _dereq_(64); var ReactServerRendering = _dereq_(98); var ReactVersion = _dereq_(108); ReactDefaultInjection.inject(); var ReactDOMServer = { renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, version: ReactVersion }; module.exports = ReactDOMServer; },{"108":108,"64":64,"98":98}],58:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextComponent */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var DOMChildrenOperations = _dereq_(7); var DOMLazyTree = _dereq_(8); var ReactDOMComponentTree = _dereq_(46); var escapeTextContentForBrowser = _dereq_(135); var invariant = _dereq_(178); var validateDOMNesting = _dereq_(161); /** * 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; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { if ("development" !== 'production') { 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('#text', 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(ownerDocument.createDocumentFragment()); DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)); if (this._stringText) { DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)); ReactDOMComponentTree.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getHostNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); } } }, getHostNode: function () { var hostNode = this._commentNodes; if (hostNode) { return hostNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? "development" !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0; if (node.nodeType === 8 && 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.uncacheNode(this); } }); module.exports = ReactDOMTextComponent; },{"135":135,"153":153,"161":161,"178":178,"188":188,"46":46,"7":7,"8":8}],59:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var DisabledInputUtils = _dereq_(14); var LinkedValueUtils = _dereq_(25); var ReactDOMComponentTree = _dereq_(46); var ReactUpdates = _dereq_(107); var invariant = _dereq_(178); var warning = _dereq_(187); var didWarnValueLink = false; var didWarnValDefaultVal = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } /** * 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) ? "development" !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : _prodInvariant('91') : 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 = _assign({}, DisabledInputUtils.getHostProps(inst, props), { value: undefined, defaultValue: undefined, children: '' + inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if ("development" !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); if (props.valueLink !== undefined && !didWarnValueLink) { "development" !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { "development" !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValDefaultVal = true; } } var value = LinkedValueUtils.getValue(props); 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) { if ("development" !== 'production') { "development" !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0; } !(defaultValue == null) ? "development" !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : _prodInvariant('92') : void 0; if (Array.isArray(children)) { !(children.length <= 1) ? "development" !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : _prodInvariant('93') : void 0; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } inst._wrapperState = { initialValue: '' + initialValue, listeners: null, onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. 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.getNodeFromInstance(inst); // Warning: node.value may be the empty string at this point (IE11) if placeholder is set. node.value = node.textContent; // Detach value from defaultValue } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; },{"107":107,"14":14,"153":153,"178":178,"187":187,"188":188,"25":25,"46":46}],60:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTreeTraversal */ 'use strict'; var _prodInvariant = _dereq_(153); var invariant = _dereq_(178); /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { !('_hostNode' in instA) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; !('_hostNode' in instB) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; var depthA = 0; for (var tempA = instA; tempA; tempA = tempA._hostParent) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = tempB._hostParent) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = instA._hostParent; depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = instB._hostParent; depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB) { return instA; } instA = instA._hostParent; instB = instB._hostParent; } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { !('_hostNode' in instA) ? "development" !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; !('_hostNode' in instB) ? "development" !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; while (instB) { if (instB === instA) { return true; } instB = instB._hostParent; } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { !('_hostNode' in inst) ? "development" !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0; return inst._hostParent; } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = inst._hostParent; } var i; for (i = path.length; i-- > 0;) { fn(path[i], false, arg); } for (i = 0; i < path.length; i++) { fn(path[i], true, arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = from._hostParent; } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = to._hostParent; } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], true, argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], false, argTo); } } module.exports = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; },{"153":153,"178":178}],61:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMUnknownPropertyHook */ 'use strict'; var DOMProperty = _dereq_(10); var EventPluginRegistry = _dereq_(18); var ReactComponentTreeHook = _dereq_(38); var warning = _dereq_(187); if ("development" !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, valueLink: true, defaultChecked: true, checkedLink: true, innerHTML: true, suppressContentEditableWarning: true, onFocusIn: true, onFocusOut: true }; var warnedProperties = {}; var validateProperty = function (tagName, name, debugID) { if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) { return true; } if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return true; } if (EventPluginRegistry.registrationNameModules.hasOwnProperty(name)) { return true; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null; if (standardName != null) { "development" !== 'production' ? warning(false, 'Unknown DOM property %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else if (registrationName != null) { "development" !== 'production' ? warning(false, 'Unknown event handler property %s. Did you mean `%s`?%s', name, registrationName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else { // We were unable to guess which prop the user intended. // It is likely that the user was just blindly spreading/forwarding props // Components should be careful to only render valid props/attributes. // Warning will be invoked in warnUnknownProperties to allow grouping. return false; } }; } var warnUnknownProperties = function (debugID, element) { var unknownProps = []; for (var key in element.props) { var isValid = validateProperty(element.type, key, debugID); if (!isValid) { unknownProps.push(key); } } var unknownPropString = unknownProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (unknownProps.length === 1) { "development" !== 'production' ? warning(false, 'Unknown prop %s on <%s> tag. Remove this prop from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } else if (unknownProps.length > 1) { "development" !== 'production' ? warning(false, 'Unknown props %s on <%s> tag. Remove these props from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } }; function handleElement(debugID, element) { if (element == null || typeof element.type !== 'string') { return; } if (element.type.indexOf('-') >= 0 || element.props.is) { return; } warnUnknownProperties(debugID, element); } var ReactDOMUnknownPropertyHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMUnknownPropertyHook; },{"10":10,"18":18,"187":187,"38":38}],62:[function(_dereq_,module,exports){ /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDebugTool */ 'use strict'; var ReactInvalidSetStateWarningHook = _dereq_(79); var ReactHostOperationHistoryHook = _dereq_(74); var ReactComponentTreeHook = _dereq_(38); var ReactChildrenMutationWarningHook = _dereq_(33); var ExecutionEnvironment = _dereq_(164); var performanceNow = _dereq_(185); var warning = _dereq_(187); var hooks = []; var didHookThrowForEvent = {}; function callHook(event, fn, context, arg1, arg2, arg3, arg4, arg5) { try { fn.call(context, arg1, arg2, arg3, arg4, arg5); } catch (e) { "development" !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0; didHookThrowForEvent[event] = true; } } function emitEvent(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 = null; var currentFlushStartTime = null; var currentTimerDebugID = null; var currentTimerStartTime = null; var currentTimerNestedFlushDuration = null; var currentTimerType = null; var lifeCycleTimerHasWarned = false; function clearHistory() { ReactComponentTreeHook.purgeUnmountedComponents(); ReactHostOperationHistoryHook.clearHistory(); } function getTreeSnapshot(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 || ReactComponentTreeHook.getOwnerID(parentID), parentID: parentID }; return tree; }, {}); } function resetMeasurements() { var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements || []; var previousOperations = ReactHostOperationHistoryHook.getHistory(); if (currentFlushNesting === 0) { currentFlushStartTime = null; currentFlushMeasurements = null; clearHistory(); return; } if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(); currentFlushStartTime = performanceNow(); currentFlushMeasurements = []; } function checkDebugID(debugID) { var allowRoot = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (allowRoot && debugID === 0) { return; } if (!debugID) { "development" !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0; } } function beginLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType && !lifeCycleTimerHasWarned) { "development" !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } currentTimerStartTime = performanceNow(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; } function endLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { "development" !== 'production' ? warning(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') : void 0; lifeCycleTimerHasWarned = true; } if (isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = null; currentTimerNestedFlushDuration = null; currentTimerDebugID = null; currentTimerType = null; } function pauseCurrentLifeCycleTimer() { var currentTimer = { startTime: currentTimerStartTime, nestedFlushStartTime: performanceNow(), debugID: currentTimerDebugID, timerType: currentTimerType }; lifeCycleTimerStack.push(currentTimer); currentTimerStartTime = null; currentTimerNestedFlushDuration = null; currentTimerDebugID = null; currentTimerType = null; } function resumeCurrentLifeCycleTimer() { var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(); var startTime = _lifeCycleTimerStack$.startTime; var nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime; var debugID = _lifeCycleTimerStack$.debugID; var timerType = _lifeCycleTimerStack$.timerType; var nestedFlushDuration = performanceNow() - nestedFlushStartTime; currentTimerStartTime = startTime; currentTimerNestedFlushDuration += nestedFlushDuration; currentTimerDebugID = debugID; currentTimerType = timerType; } var ReactDebugTool = { 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.addHook(ReactHostOperationHistoryHook); }, endProfiling: function () { if (!isProfiling) { return; } isProfiling = false; resetMeasurements(); ReactDebugTool.removeHook(ReactHostOperationHistoryHook); }, 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); beginLifeCycleTimer(debugID, timerType); }, onEndLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); endLifeCycleTimer(debugID, timerType); emitEvent('onEndLifeCycleTimer', debugID, timerType); }, onError: function (debugID) { if (currentTimerDebugID != null) { endLifeCycleTimer(currentTimerDebugID, currentTimerType); } emitEvent('onError', debugID); }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onHostOperation: function (debugID, type, payload) { checkDebugID(debugID); emitEvent('onHostOperation', debugID, type, payload); }, 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); }, onMountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onMountComponent', debugID); }, onBeforeUpdateComponent: function (debugID, element) { checkDebugID(debugID); emitEvent('onBeforeUpdateComponent', debugID, element); }, onUpdateComponent: function (debugID) { checkDebugID(debugID); emitEvent('onUpdateComponent', debugID); }, onBeforeUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onBeforeUnmountComponent', debugID); }, onUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onUnmountComponent', debugID); }, onTestEvent: function () { emitEvent('onTestEvent'); } }; // TODO remove these when RN/www gets updated ReactDebugTool.addDevtool = ReactDebugTool.addHook; ReactDebugTool.removeDevtool = ReactDebugTool.removeHook; ReactDebugTool.addHook(ReactInvalidSetStateWarningHook); ReactDebugTool.addHook(ReactComponentTreeHook); ReactDebugTool.addHook(ReactChildrenMutationWarningHook); var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { ReactDebugTool.beginProfiling(); } module.exports = ReactDebugTool; },{"164":164,"185":185,"187":187,"33":33,"38":38,"74":74,"79":79}],63:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ 'use strict'; var _assign = _dereq_(188); var ReactUpdates = _dereq_(107); var Transaction = _dereq_(127); var emptyFunction = _dereq_(170); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } _assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; },{"107":107,"127":127,"170":170,"188":188}],64:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ 'use strict'; var BeforeInputEventPlugin = _dereq_(2); var ChangeEventPlugin = _dereq_(6); var DefaultEventPluginOrder = _dereq_(13); var EnterLeaveEventPlugin = _dereq_(15); var HTMLDOMPropertyConfig = _dereq_(22); var ReactComponentBrowserEnvironment = _dereq_(36); var ReactDOMComponent = _dereq_(44); var ReactDOMComponentTree = _dereq_(46); var ReactDOMEmptyComponent = _dereq_(48); var ReactDOMTreeTraversal = _dereq_(60); var ReactDOMTextComponent = _dereq_(58); var ReactDefaultBatchingStrategy = _dereq_(63); var ReactEventListener = _dereq_(70); var ReactInjection = _dereq_(75); var ReactReconcileTransaction = _dereq_(94); var SVGDOMPropertyConfig = _dereq_(111); var SelectEventPlugin = _dereq_(112); var SimpleEventPlugin = _dereq_(113); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree); ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.HostComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent(instantiate); }); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); } module.exports = { inject: inject }; },{"111":111,"112":112,"113":113,"13":13,"15":15,"2":2,"22":22,"36":36,"44":44,"46":46,"48":48,"58":58,"6":6,"60":60,"63":63,"70":70,"75":75,"94":94}],65:[function(_dereq_,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var _assign = _dereq_(188); var ReactCurrentOwner = _dereq_(41); var warning = _dereq_(187); var canDefineProperty = _dereq_(131); var hasOwnProperty = Object.prototype.hasOwnProperty; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; function hasValidRef(config) { if ("development" !== 'production') { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { if ("development" !== 'production') { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; "development" !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; "development" !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if ("development" !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; var shadowChildren = Array.isArray(props.children) ? props.children.slice(0) : props.children; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); Object.defineProperty(element, '_shadowChildren', { configurable: false, enumerable: false, writable: false, value: shadowChildren }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._shadowChildren = shadowChildren; element._source = source; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if ("development" !== 'production') { "development" !== 'production' ? warning( /* eslint-disable no-proto */ config.__proto__ == null || config.__proto__ === Object.prototype, /* eslint-enable no-proto */ 'React.createElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0; } if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if ("development" !== 'production') { if (key || ref) { if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if ("development" !== 'production') { "development" !== 'production' ? warning( /* eslint-disable no-proto */ config.__proto__ == null || config.__proto__ === Object.prototype, /* eslint-enable no-proto */ 'React.cloneElement(...): Expected props argument to be a plain object. ' + 'Properties defined in its prototype chain will be ignored.') : void 0; } if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; ReactElement.REACT_ELEMENT_TYPE = REACT_ELEMENT_TYPE; module.exports = ReactElement; },{"131":131,"187":187,"188":188,"41":41}],66:[function(_dereq_,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactCurrentOwner = _dereq_(41); var ReactComponentTreeHook = _dereq_(38); var ReactElement = _dereq_(65); var ReactPropTypeLocations = _dereq_(90); var checkReactTypeSpec = _dereq_(132); var canDefineProperty = _dereq_(131); var getIteratorFn = _dereq_(144); var warning = _dereq_(187); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = ' Check the top-level render call using <' + parentName + '>.'; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {}); var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (memoizer[currentComponentErrorInfo]) { return; } memoizer[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } "development" !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkReactTypeSpec(componentClass.propTypes, element.props, ReactPropTypeLocations.prop, name, element, null); } if (typeof componentClass.getDefaultProps === 'function') { "development" !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { "development" !== 'production' ? warning(false, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : void 0; } var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if ("development" !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { "development" !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; },{"131":131,"132":132,"144":144,"187":187,"38":38,"41":41,"65":65,"90":90}],67:[function(_dereq_,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponent */ 'use strict'; var emptyComponentFactory; var ReactEmptyComponentInjection = { injectEmptyComponentFactory: function (factory) { emptyComponentFactory = factory; } }; var ReactEmptyComponent = { create: function (instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; },{}],68:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactErrorUtils */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {?String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a, b) { try { return func(a, b); } catch (x) { if (caughtError === null) { caughtError = x; } return undefined; } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if ("development" !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) { var boundFunc = func.bind(null, a, b); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; },{}],69:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ 'use strict'; var EventPluginHub = _dereq_(17); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"17":17}],70:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener */ 'use strict'; var _assign = _dereq_(188); var EventListener = _dereq_(163); var ExecutionEnvironment = _dereq_(164); var PooledClass = _dereq_(26); var ReactDOMComponentTree = _dereq_(46); var ReactUpdates = _dereq_(107); var getEventTarget = _dereq_(142); var getUnboundedScrollPosition = _dereq_(175); /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findParent(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. while (inst._hostParent) { inst = inst._hostParent; } var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst); var container = rootNode.parentNode; return ReactDOMComponentTree.getClosestInstanceFromNode(container); } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } _assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent); var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget); // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = targetInst; do { bookKeeping.ancestors.push(ancestor); ancestor = ancestor && findParent(ancestor); } while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) { targetInst = bookKeeping.ancestors[i]; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; },{"107":107,"142":142,"163":163,"164":164,"175":175,"188":188,"26":26,"46":46}],71:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactFeatureFlags * */ 'use strict'; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false }; module.exports = ReactFeatureFlags; },{}],72:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactFragment */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactChildren = _dereq_(32); var ReactElement = _dereq_(65); var emptyFunction = _dereq_(170); var invariant = _dereq_(178); var warning = _dereq_(187); /** * We used to allow keyed objects to serve as a collection of ReactElements, * or nested sets. This allowed us a way to explicitly key a set or fragment of * components. This is now being replaced with an opaque data structure. * The upgrade path is to call React.addons.createFragment({ key: value }) to * create a keyed fragment. The resulting data structure is an array. */ var numericPropertyRegex = /^\d+$/; var warnedAboutNumeric = false; var ReactFragment = { /** * Wrap a keyed object in an opaque proxy that warns you if you access any * of its properties. * See https://facebook.github.io/react/docs/create-fragment.html */ create: function (object) { if (typeof object !== 'object' || !object || Array.isArray(object)) { "development" !== 'production' ? warning(false, 'React.addons.createFragment only accepts a single object. Got: %s', object) : void 0; return object; } if (ReactElement.isValidElement(object)) { "development" !== 'production' ? warning(false, 'React.addons.createFragment does not accept a ReactElement ' + 'without a wrapper object.') : void 0; return object; } !(object.nodeType !== 1) ? "development" !== 'production' ? invariant(false, 'React.addons.createFragment(...): Encountered an invalid child; DOM elements are not valid children of React components.') : _prodInvariant('0') : void 0; var result = []; for (var key in object) { if ("development" !== 'production') { if (!warnedAboutNumeric && numericPropertyRegex.test(key)) { "development" !== 'production' ? warning(false, 'React.addons.createFragment(...): Child objects should have ' + 'non-numeric keys so ordering is preserved.') : void 0; warnedAboutNumeric = true; } } ReactChildren.mapIntoWithKeyPrefixInternal(object[key], result, key, emptyFunction.thatReturnsArgument); } return result; } }; module.exports = ReactFragment; },{"153":153,"170":170,"178":178,"187":187,"32":32,"65":65}],73:[function(_dereq_,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactHostComponent */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var invariant = _dereq_(178); var genericComponentClass = null; // This registry keeps track of wrapper classes around host tags. var tagToComponentClass = {}; 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; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function (componentClasses) { _assign(tagToComponentClass, componentClasses); } }; /** * Get a 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 ? "development" !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : _prodInvariant('111', 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 }; module.exports = ReactHostComponent; },{"153":153,"178":178,"188":188}],74:[function(_dereq_,module,exports){ /** * 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 */ 'use strict'; var history = []; var ReactHostOperationHistoryHook = { onHostOperation: function (debugID, type, payload) { history.push({ instanceID: debugID, type: type, payload: payload }); }, clearHistory: function () { if (ReactHostOperationHistoryHook._preventClearing) { // Should only be used for tests. return; } history = []; }, getHistory: function () { return history; } }; module.exports = ReactHostOperationHistoryHook; },{}],75:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ 'use strict'; var DOMProperty = _dereq_(10); var EventPluginHub = _dereq_(17); var EventPluginUtils = _dereq_(19); var ReactComponentEnvironment = _dereq_(37); var ReactClass = _dereq_(34); var ReactEmptyComponent = _dereq_(67); var ReactBrowserEventEmitter = _dereq_(28); var ReactHostComponent = _dereq_(73); var ReactUpdates = _dereq_(107); var ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventPluginUtils: EventPluginUtils.injection, EventEmitter: ReactBrowserEventEmitter.injection, HostComponent: ReactHostComponent.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"10":10,"107":107,"17":17,"19":19,"28":28,"34":34,"37":37,"67":67,"73":73}],76:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ 'use strict'; var ReactDOMSelection = _dereq_(56); var containsNode = _dereq_(167); var focusNode = _dereq_(172); var getActiveElement = _dereq_(173); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; },{"167":167,"172":172,"173":173,"56":56}],77:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceMap */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; },{}],78:[function(_dereq_,module,exports){ /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstrumentation */ 'use strict'; var debugTool = null; if ("development" !== 'production') { var ReactDebugTool = _dereq_(62); debugTool = ReactDebugTool; } module.exports = { debugTool: debugTool }; },{"62":62}],79:[function(_dereq_,module,exports){ /** * 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 ReactInvalidSetStateWarningHook */ 'use strict'; var warning = _dereq_(187); if ("development" !== 'production') { var processingChildContext = false; var warnInvalidSetState = function () { "development" !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0; }; } var ReactInvalidSetStateWarningHook = { onBeginProcessingChildContext: function () { processingChildContext = true; }, onEndProcessingChildContext: function () { processingChildContext = false; }, onSetState: function () { warnInvalidSetState(); } }; module.exports = ReactInvalidSetStateWarningHook; },{"187":187}],80:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactLink */ 'use strict'; /** * ReactLink encapsulates a common pattern in which a component wants to modify * a prop received from its parent. ReactLink allows the parent to pass down a * value coupled with a callback that, when invoked, expresses an intent to * modify that value. For example: * * React.createClass({ * getInitialState: function() { * return {value: ''}; * }, * render: function() { * var valueLink = new ReactLink(this.state.value, this._handleValueChange); * return <input valueLink={valueLink} />; * }, * _handleValueChange: function(newValue) { * this.setState({value: newValue}); * } * }); * * We have provided some sugary mixins to make the creation and * consumption of ReactLink easier; see LinkedValueUtils and LinkedStateMixin. */ var React = _dereq_(27); /** * Deprecated: An an easy way to express two-way binding with React. * See https://facebook.github.io/react/docs/two-way-binding-helpers.html * * @param {*} value current value of the link * @param {function} requestChange callback to request a change */ function ReactLink(value, requestChange) { this.value = value; this.requestChange = requestChange; } /** * Creates a PropType that enforces the ReactLink API and optionally checks the * type of the value being passed inside the link. Example: * * MyComponent.propTypes = { * tabIndexLink: ReactLink.PropTypes.link(React.PropTypes.number) * } */ function createLinkTypeChecker(linkType) { var shapes = { value: linkType === undefined ? React.PropTypes.any.isRequired : linkType.isRequired, requestChange: React.PropTypes.func.isRequired }; return React.PropTypes.shape(shapes); } ReactLink.PropTypes = { link: createLinkTypeChecker }; module.exports = ReactLink; },{"27":27}],81:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ 'use strict'; var adler32 = _dereq_(130); var TAG_END = /\/?>/; var COMMENT_START = /^<\!\-\-/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags, comments and self-closing tags) if (COMMENT_START.test(markup)) { return markup; } else { return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); } }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; },{"130":130}],82:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMount */ 'use strict'; var _prodInvariant = _dereq_(153); var DOMLazyTree = _dereq_(8); var DOMProperty = _dereq_(10); var ReactBrowserEventEmitter = _dereq_(28); var ReactCurrentOwner = _dereq_(41); var ReactDOMComponentTree = _dereq_(46); var ReactDOMContainerInfo = _dereq_(47); var ReactDOMFeatureFlags = _dereq_(50); var ReactElement = _dereq_(65); var ReactFeatureFlags = _dereq_(71); var ReactInstanceMap = _dereq_(77); var ReactInstrumentation = _dereq_(78); var ReactMarkupChecksum = _dereq_(81); var ReactReconciler = _dereq_(95); var ReactUpdateQueue = _dereq_(106); var ReactUpdates = _dereq_(107); var emptyObject = _dereq_(171); var instantiateReactComponent = _dereq_(148); var invariant = _dereq_(178); var setInnerHTML = _dereq_(155); var shouldUpdateReactComponent = _dereq_(158); var warning = _dereq_(187); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var instancesByReactRootID = {}; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) { var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var wrappedElement = wrapperInstance._currentElement.props; var type = wrappedElement.type; markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name); console.time(markerName); } var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context, 0 /* parentDebugID */ ); if (markerName) { console.timeEnd(markerName); } wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance; ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container, safely) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onBeginFlush(); } ReactReconciler.unmountComponent(instance, safely); if ("development" !== 'production') { ReactInstrumentation.debugTool.onEndFlush(); } if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._hostParent); } } /** * True if the supplied DOM node is a React DOM element and * it has been rendered by another copy of React. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM has been rendered by another copy of React * @internal */ function nodeIsRenderedByOtherInstance(container) { var rootEl = getReactRootElementInContainer(container); return !!(rootEl && isReactNode(rootEl) && !ReactDOMComponentTree.getInstanceFromNode(rootEl)); } /** * True if the supplied DOM node is a valid node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid DOM node. * @internal */ function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE_TYPE || node.nodeType === DOC_NODE_TYPE || node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)); } /** * True if the supplied DOM node is a valid React node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid React DOM node. * @internal */ function isReactNode(node) { return isValidContainer(node) && (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME)); } function getHostRootInstanceInContainer(container) { var rootEl = getReactRootElementInContainer(container); var prevHostInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl); return prevHostInstance && !prevHostInstance._hostParent ? prevHostInstance : null; } function getTopLevelWrapperInContainer(container) { var root = getHostRootInstanceInContainer(container); return root ? root._hostContainerInfo._topLevelWrapper : null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var topLevelRootCounter = 1; var TopLevelWrapper = function () { this.rootID = topLevelRootCounter++; }; TopLevelWrapper.prototype.isReactComponent = {}; if ("development" !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { // this.props is actually a ReactElement return this.props; }; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** * Used by devtools. The keys are not important. */ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, nextContext, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement, nextContext); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); return prevComponent; }, /** * Render a new component into the DOM. Hooked by hooks! * * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. "development" !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? "development" !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement, false); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && ReactInstanceMap.has(parentComponent)) ? "development" !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : _prodInvariant('38') : void 0; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render'); !ReactElement.isValidElement(nextElement) ? "development" !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : _prodInvariant('39', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : void 0; "development" !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0; var nextWrappedElement = ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement); var nextContext; if (parentComponent) { var parentInst = ReactInstanceMap.get(parentComponent); nextContext = parentInst._processChildContext(parentInst._context); } else { nextContext = emptyObject; } var prevComponent = getTopLevelWrapperInContainer(container); if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, nextContext, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if ("development" !== 'production') { "development" !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { "development" !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : void 0; break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, nextContext)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.render * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Unmounts and destroys the React component rendered in the `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.unmountcomponentatnode * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) "development" !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? "development" !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : _prodInvariant('40') : void 0; if ("development" !== 'production') { "development" !== 'production' ? warning(!nodeIsRenderedByOtherInstance(container), 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by another copy of React.') : void 0; } var prevComponent = getTopLevelWrapperInContainer(container); if (!prevComponent) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME); if ("development" !== 'production') { "development" !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0; } return false; } delete instancesByReactRootID[prevComponent._instance.rootID]; ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false); return true; }, _mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) { !isValidContainer(container) ? "development" !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : _prodInvariant('41') : void 0; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { ReactDOMComponentTree.precacheNode(instance, rootElement); return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if ("development" !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s', difference) : _prodInvariant('42', difference) : void 0; if ("development" !== 'production') { "development" !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : void 0; } } } !(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but you didn\'t use server rendering. We can\'t do this without using server rendering due to cross-browser quirks. See ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('43') : void 0; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } DOMLazyTree.insertTreeBefore(container, markup, null); } else { setInnerHTML(container, markup); ReactDOMComponentTree.precacheNode(instance, container.firstChild); } if ("development" !== 'production') { var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild); if (hostNode._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation(hostNode._debugID, 'mount', markup.toString()); } } } }; module.exports = ReactMount; },{"10":10,"106":106,"107":107,"148":148,"153":153,"155":155,"158":158,"171":171,"178":178,"187":187,"28":28,"41":41,"46":46,"47":47,"50":50,"65":65,"71":71,"77":77,"78":78,"8":8,"81":81,"95":95}],83:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactComponentEnvironment = _dereq_(37); var ReactInstanceMap = _dereq_(77); var ReactInstrumentation = _dereq_(78); var ReactMultiChildUpdateTypes = _dereq_(84); var ReactCurrentOwner = _dereq_(41); var ReactReconciler = _dereq_(95); var ReactChildReconciler = _dereq_(31); var emptyFunction = _dereq_(170); var flattenChildren = _dereq_(137); var invariant = _dereq_(178); /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.INSERT_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.MOVE_EXISTING, content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.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: ReactMultiChildUpdateTypes.REMOVE_NODE, content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.SET_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.TEXT_CONTENT, content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue); } var setChildrenForInstrumentation = emptyFunction; if ("development" !== 'production') { var getDebugID = function (inst) { if (!inst._debugID) { // Check for ART-like instances. TODO: This is silly/gross. var internal; if (internal = ReactInstanceMap.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; }) : []); } }; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if ("development" !== 'production') { var selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context, selfDebugID); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) { var nextChildren; var selfDebugID = 0; if ("development" !== 'production') { selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); } finally { ReactCurrentOwner.current = null; } ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; } } nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); ReactChildReconciler.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; if ("development" !== 'production') { selfDebugID = getDebugID(this); } var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID); child._mountIndex = index++; mountImages.push(mountImage); } } if ("development" !== 'production') { 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.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { !false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } // Set new text content. var updates = [makeTextContent(nextContent)]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { !false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var removedNodes = {}; var 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.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; if ("development" !== 'production') { 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) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { return makeMove(child, afterNode, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function (child, 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; } } }; module.exports = ReactMultiChild; },{"137":137,"153":153,"170":170,"178":178,"31":31,"37":37,"41":41,"77":77,"78":78,"84":84,"95":95}],84:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ 'use strict'; var keyMirror = _dereq_(181); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, SET_MARKUP: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; },{"181":181}],85:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNodeTypes * */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactElement = _dereq_(65); var invariant = _dereq_(178); var ReactNodeTypes = { HOST: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (ReactElement.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.HOST; } } !false ? "development" !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0; } }; module.exports = ReactNodeTypes; },{"153":153,"178":178,"65":65}],86:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNoopUpdateQueue */ 'use strict'; var warning = _dereq_(187); function warnNoop(publicInstance, callerName) { if ("development" !== 'production') { var constructor = publicInstance.constructor; "development" !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { 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} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { 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} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnNoop(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; },{"187":187}],87:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ 'use strict'; var _prodInvariant = _dereq_(153); var invariant = _dereq_(178); /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function (object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('119') : void 0; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('120') : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; },{"153":153,"178":178}],88:[function(_dereq_,module,exports){ /** * 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 ReactPerf */ 'use strict'; var _assign = _dereq_(188); var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var ReactDebugTool = _dereq_(62); var warning = _dereq_(187); var alreadyWarned = false; function roundFloat(val) { var base = arguments.length <= 1 || arguments[1] === undefined ? 2 : arguments[1]; var n = Math.pow(10, base); return Math.floor(val * n) / n; } function warnInProduction() { if (alreadyWarned) { return; } alreadyWarned = true; if (typeof console !== 'undefined') { console.error('ReactPerf is not supported in the production builds of React. ' + 'To collect measurements, please use the development build of React instead.'); } } function getLastMeasurements() { if (!("development" !== 'production')) { warnInProduction(); return []; } return ReactDebugTool.getFlushHistory(); } function getExclusive() { var flushHistory = arguments.length <= 0 || arguments[0] === undefined ? getLastMeasurements() : arguments[0]; if (!("development" !== 'production')) { warnInProduction(); return []; } var aggregatedStats = {}; var affectedIDs = {}; function updateAggregatedStats(treeSnapshot, instanceID, timerType, applyUpdate) { var displayName = treeSnapshot[instanceID].displayName; var key = displayName; var stats = aggregatedStats[key]; if (!stats) { affectedIDs[key] = {}; stats = aggregatedStats[key] = { key: key, instanceCount: 0, counts: {}, durations: {}, totalDuration: 0 }; } if (!stats.durations[timerType]) { stats.durations[timerType] = 0; } if (!stats.counts[timerType]) { stats.counts[timerType] = 0; } affectedIDs[key][instanceID] = true; applyUpdate(stats); } flushHistory.forEach(function (flush) { var measurements = flush.measurements; var treeSnapshot = flush.treeSnapshot; measurements.forEach(function (measurement) { var duration = measurement.duration; var instanceID = measurement.instanceID; var timerType = measurement.timerType; updateAggregatedStats(treeSnapshot, instanceID, timerType, function (stats) { stats.totalDuration += duration; stats.durations[timerType] += duration; stats.counts[timerType]++; }); }); }); return Object.keys(aggregatedStats).map(function (key) { return _extends({}, aggregatedStats[key], { instanceCount: Object.keys(affectedIDs[key]).length }); }).sort(function (a, b) { return b.totalDuration - a.totalDuration; }); } function getInclusive() { var flushHistory = arguments.length <= 0 || arguments[0] === undefined ? getLastMeasurements() : arguments[0]; if (!("development" !== 'production')) { warnInProduction(); return []; } var aggregatedStats = {}; var affectedIDs = {}; function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) { var _treeSnapshot$instanc = treeSnapshot[instanceID]; var displayName = _treeSnapshot$instanc.displayName; var ownerID = _treeSnapshot$instanc.ownerID; var owner = treeSnapshot[ownerID]; var key = (owner ? owner.displayName + ' > ' : '') + displayName; var stats = aggregatedStats[key]; if (!stats) { affectedIDs[key] = {}; stats = aggregatedStats[key] = { key: key, instanceCount: 0, inclusiveRenderDuration: 0, renderCount: 0 }; } affectedIDs[key][instanceID] = true; applyUpdate(stats); } var isCompositeByID = {}; flushHistory.forEach(function (flush) { var measurements = flush.measurements; measurements.forEach(function (measurement) { var instanceID = measurement.instanceID; var timerType = measurement.timerType; if (timerType !== 'render') { return; } isCompositeByID[instanceID] = true; }); }); flushHistory.forEach(function (flush) { var measurements = flush.measurements; var treeSnapshot = flush.treeSnapshot; measurements.forEach(function (measurement) { var duration = measurement.duration; var instanceID = measurement.instanceID; var timerType = measurement.timerType; if (timerType !== 'render') { return; } updateAggregatedStats(treeSnapshot, instanceID, function (stats) { stats.renderCount++; }); var nextParentID = instanceID; while (nextParentID) { // As we traverse parents, only count inclusive time towards composites. // We know something is a composite if its render() was called. if (isCompositeByID[nextParentID]) { updateAggregatedStats(treeSnapshot, nextParentID, function (stats) { stats.inclusiveRenderDuration += duration; }); } nextParentID = treeSnapshot[nextParentID].parentID; } }); }); return Object.keys(aggregatedStats).map(function (key) { return _extends({}, aggregatedStats[key], { instanceCount: Object.keys(affectedIDs[key]).length }); }).sort(function (a, b) { return b.inclusiveRenderDuration - a.inclusiveRenderDuration; }); } function getWasted() { var flushHistory = arguments.length <= 0 || arguments[0] === undefined ? getLastMeasurements() : arguments[0]; if (!("development" !== 'production')) { warnInProduction(); return []; } var aggregatedStats = {}; var affectedIDs = {}; function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) { var _treeSnapshot$instanc2 = treeSnapshot[instanceID]; var displayName = _treeSnapshot$instanc2.displayName; var ownerID = _treeSnapshot$instanc2.ownerID; var owner = treeSnapshot[ownerID]; var key = (owner ? owner.displayName + ' > ' : '') + displayName; var stats = aggregatedStats[key]; if (!stats) { affectedIDs[key] = {}; stats = aggregatedStats[key] = { key: key, instanceCount: 0, inclusiveRenderDuration: 0, renderCount: 0 }; } affectedIDs[key][instanceID] = true; applyUpdate(stats); } flushHistory.forEach(function (flush) { var measurements = flush.measurements; var treeSnapshot = flush.treeSnapshot; var operations = flush.operations; var isDefinitelyNotWastedByID = {}; // Find host components associated with an operation in this batch. // Mark all components in their parent tree as definitely not wasted. operations.forEach(function (operation) { var instanceID = operation.instanceID; var nextParentID = instanceID; while (nextParentID) { isDefinitelyNotWastedByID[nextParentID] = true; nextParentID = treeSnapshot[nextParentID].parentID; } }); // Find composite components that rendered in this batch. // These are potential candidates for being wasted renders. var renderedCompositeIDs = {}; measurements.forEach(function (measurement) { var instanceID = measurement.instanceID; var timerType = measurement.timerType; if (timerType !== 'render') { return; } renderedCompositeIDs[instanceID] = true; }); measurements.forEach(function (measurement) { var duration = measurement.duration; var instanceID = measurement.instanceID; var timerType = measurement.timerType; if (timerType !== 'render') { return; } // If there was a DOM update below this component, or it has just been // mounted, its render() is not considered wasted. var updateCount = treeSnapshot[instanceID].updateCount; if (isDefinitelyNotWastedByID[instanceID] || updateCount === 0) { return; } // We consider this render() wasted. updateAggregatedStats(treeSnapshot, instanceID, function (stats) { stats.renderCount++; }); var nextParentID = instanceID; while (nextParentID) { // Any parents rendered during this batch are considered wasted // unless we previously marked them as dirty. var isWasted = renderedCompositeIDs[nextParentID] && !isDefinitelyNotWastedByID[nextParentID]; if (isWasted) { updateAggregatedStats(treeSnapshot, nextParentID, function (stats) { stats.inclusiveRenderDuration += duration; }); } nextParentID = treeSnapshot[nextParentID].parentID; } }); }); return Object.keys(aggregatedStats).map(function (key) { return _extends({}, aggregatedStats[key], { instanceCount: Object.keys(affectedIDs[key]).length }); }).sort(function (a, b) { return b.inclusiveRenderDuration - a.inclusiveRenderDuration; }); } function getOperations() { var flushHistory = arguments.length <= 0 || arguments[0] === undefined ? getLastMeasurements() : arguments[0]; if (!("development" !== 'production')) { warnInProduction(); return []; } var stats = []; flushHistory.forEach(function (flush, flushIndex) { var operations = flush.operations; var treeSnapshot = flush.treeSnapshot; operations.forEach(function (operation) { var instanceID = operation.instanceID; var type = operation.type; var payload = operation.payload; var _treeSnapshot$instanc3 = treeSnapshot[instanceID]; var displayName = _treeSnapshot$instanc3.displayName; var ownerID = _treeSnapshot$instanc3.ownerID; var owner = treeSnapshot[ownerID]; var key = (owner ? owner.displayName + ' > ' : '') + displayName; stats.push({ flushIndex: flushIndex, instanceID: instanceID, key: key, type: type, ownerID: ownerID, payload: payload }); }); }); return stats; } function printExclusive(flushHistory) { if (!("development" !== 'production')) { warnInProduction(); return; } var stats = getExclusive(flushHistory); var table = stats.map(function (item) { var key = item.key; var instanceCount = item.instanceCount; var totalDuration = item.totalDuration; var renderCount = item.counts.render || 0; var renderDuration = item.durations.render || 0; return { 'Component': key, 'Total time (ms)': roundFloat(totalDuration), 'Instance count': instanceCount, 'Total render time (ms)': roundFloat(renderDuration), 'Average render time (ms)': renderCount ? roundFloat(renderDuration / renderCount) : undefined, 'Render count': renderCount, 'Total lifecycle time (ms)': roundFloat(totalDuration - renderDuration) }; }); console.table(table); } function printInclusive(flushHistory) { if (!("development" !== 'production')) { warnInProduction(); return; } var stats = getInclusive(flushHistory); var table = stats.map(function (item) { var key = item.key; var instanceCount = item.instanceCount; var inclusiveRenderDuration = item.inclusiveRenderDuration; var renderCount = item.renderCount; return { 'Owner > Component': key, 'Inclusive render time (ms)': roundFloat(inclusiveRenderDuration), 'Instance count': instanceCount, 'Render count': renderCount }; }); console.table(table); } function printWasted(flushHistory) { if (!("development" !== 'production')) { warnInProduction(); return; } var stats = getWasted(flushHistory); var table = stats.map(function (item) { var key = item.key; var instanceCount = item.instanceCount; var inclusiveRenderDuration = item.inclusiveRenderDuration; var renderCount = item.renderCount; return { 'Owner > Component': key, 'Inclusive wasted time (ms)': roundFloat(inclusiveRenderDuration), 'Instance count': instanceCount, 'Render count': renderCount }; }); console.table(table); } function printOperations(flushHistory) { if (!("development" !== 'production')) { warnInProduction(); return; } var stats = getOperations(flushHistory); var table = stats.map(function (stat) { return { 'Owner > Node': stat.key, 'Operation': stat.type, 'Payload': typeof stat.payload === 'object' ? JSON.stringify(stat.payload) : stat.payload, 'Flush index': stat.flushIndex, 'Owner Component ID': stat.ownerID, 'DOM Component ID': stat.instanceID }; }); console.table(table); } var warnedAboutPrintDOM = false; function printDOM(measurements) { "development" !== 'production' ? warning(warnedAboutPrintDOM, '`ReactPerf.printDOM(...)` is deprecated. Use ' + '`ReactPerf.printOperations(...)` instead.') : void 0; warnedAboutPrintDOM = true; return printOperations(measurements); } var warnedAboutGetMeasurementsSummaryMap = false; function getMeasurementsSummaryMap(measurements) { "development" !== 'production' ? warning(warnedAboutGetMeasurementsSummaryMap, '`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use ' + '`ReactPerf.getWasted(...)` instead.') : void 0; warnedAboutGetMeasurementsSummaryMap = true; return getWasted(measurements); } function start() { if (!("development" !== 'production')) { warnInProduction(); return; } ReactDebugTool.beginProfiling(); } function stop() { if (!("development" !== 'production')) { warnInProduction(); return; } ReactDebugTool.endProfiling(); } function isRunning() { if (!("development" !== 'production')) { warnInProduction(); return false; } return ReactDebugTool.isProfiling(); } var ReactPerfAnalysis = { getLastMeasurements: getLastMeasurements, getExclusive: getExclusive, getInclusive: getInclusive, getWasted: getWasted, getOperations: getOperations, printExclusive: printExclusive, printInclusive: printInclusive, printWasted: printWasted, printOperations: printOperations, start: start, stop: stop, isRunning: isRunning, // Deprecated: printDOM: printDOM, getMeasurementsSummaryMap: getMeasurementsSummaryMap }; module.exports = ReactPerfAnalysis; },{"187":187,"188":188,"62":62}],89:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ 'use strict'; var ReactPropTypeLocationNames = {}; if ("development" !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; },{}],90:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ 'use strict'; var keyMirror = _dereq_(181); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"181":181}],91:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ 'use strict'; var ReactElement = _dereq_(65); var ReactPropTypeLocationNames = _dereq_(89); var ReactPropTypesSecret = _dereq_(92); var emptyFunction = _dereq_(170); var getIteratorFn = _dereq_(144); var warning = _dereq_(187); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), 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) { if ("development" !== 'production') { var manualPropTypeCallCache = {}; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if ("development" !== 'production') { if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') { var cacheKey = componentName + ':' + propName; if (!manualPropTypeCallCache[cacheKey]) { "development" !== 'production' ? warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will not work in the next major version. 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) : void 0; manualPropTypeCallCache[cacheKey] = true; } } } if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new PropTypeError('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); 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 (!ReactElement.isValidElement(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + 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 locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { "development" !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.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 locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { "development" !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.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) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } 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; } module.exports = ReactPropTypes; },{"144":144,"170":170,"187":187,"65":65,"89":89,"92":92}],92:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypesSecret */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; },{}],93:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPureComponent */ 'use strict'; var _assign = _dereq_(188); var ReactComponent = _dereq_(35); var ReactNoopUpdateQueue = _dereq_(86); var emptyObject = _dereq_(171); /** * Base class helpers for the updating state of a component. */ function ReactPureComponent(props, context, updater) { // Duplicated from ReactComponent. this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. _assign(ReactPureComponent.prototype, ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; module.exports = ReactPureComponent; },{"171":171,"188":188,"35":35,"86":86}],94:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction */ 'use strict'; var _assign = _dereq_(188); var CallbackQueue = _dereq_(5); var PooledClass = _dereq_(26); var ReactBrowserEventEmitter = _dereq_(28); var ReactInputSelection = _dereq_(76); var ReactInstrumentation = _dereq_(78); var Transaction = _dereq_(127); var ReactUpdateQueue = _dereq_(106); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; if ("development" !== 'production') { TRANSACTION_WRAPPERS.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.getPooled(null); this.useCreateElement = useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return ReactUpdateQueue; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function () { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function (checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; _assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"106":106,"127":127,"188":188,"26":26,"28":28,"5":5,"76":76,"78":78}],95:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ 'use strict'; var ReactRef = _dereq_(96); var ReactInstrumentation = _dereq_(78); var warning = _dereq_(187); /** * 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, parentDebugID // 0 in production and for roots ) { if ("development" !== 'production') { 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 ("development" !== 'production') { 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) { if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if ("development" !== 'production') { 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 ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement); } } 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 ("development" !== 'production') { 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. "development" !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if ("development" !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; module.exports = ReactReconciler; },{"187":187,"78":78,"96":96}],96:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRef */ 'use strict'; var ReactOwner = _dereq_(87); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; return ( // This has a few false positives w/r/t empty components. prevEmpty || nextEmpty || nextElement.ref !== prevElement.ref || // If owner changes but we have an unchanged function ref, don't update refs typeof nextElement.ref === 'string' && nextElement._owner !== prevElement._owner ); }; ReactRef.detachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; },{"87":87}],97:[function(_dereq_,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerBatchingStrategy */ 'use strict'; 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. } }; module.exports = ReactServerBatchingStrategy; },{}],98:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRendering */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactDOMContainerInfo = _dereq_(47); var ReactDefaultBatchingStrategy = _dereq_(63); var ReactElement = _dereq_(65); var ReactInstrumentation = _dereq_(78); var ReactMarkupChecksum = _dereq_(81); var ReactReconciler = _dereq_(95); var ReactServerBatchingStrategy = _dereq_(97); var ReactServerRenderingTransaction = _dereq_(99); var ReactUpdates = _dereq_(107); var emptyObject = _dereq_(171); var instantiateReactComponent = _dereq_(148); var invariant = _dereq_(178); var pendingTransactions = 0; /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToStringImpl(element, makeStaticMarkup) { var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup); pendingTransactions++; return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, true); var markup = ReactReconciler.mountComponent(componentInstance, transaction, null, ReactDOMContainerInfo(), emptyObject, 0 /* parentDebugID */ ); if ("development" !== 'production') { ReactInstrumentation.debugTool.onUnmountComponent(componentInstance._debugID); } if (!makeStaticMarkup) { markup = ReactMarkupChecksum.addChecksumToMarkup(markup); } return markup; }, null); } finally { pendingTransactions--; ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. if (!pendingTransactions) { ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } } /** * Render a ReactElement to its initial HTML. This should only be used on the * server. * See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring */ function renderToString(element) { !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : _prodInvariant('46') : 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/top-level-api.html#reactdomserver.rendertostaticmarkup */ function renderToStaticMarkup(element) { !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : _prodInvariant('47') : void 0; return renderToStringImpl(element, true); } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; },{"107":107,"148":148,"153":153,"171":171,"178":178,"47":47,"63":63,"65":65,"78":78,"81":81,"95":95,"97":97,"99":99}],99:[function(_dereq_,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRenderingTransaction */ 'use strict'; var _assign = _dereq_(188); var PooledClass = _dereq_(26); var Transaction = _dereq_(127); var ReactInstrumentation = _dereq_(78); var ReactServerUpdateQueue = _dereq_(100); /** * 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 = []; if ("development" !== 'production') { 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(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 () {} }; _assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"100":100,"127":127,"188":188,"26":26,"78":78}],100:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerUpdateQueue * */ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ReactUpdateQueue = _dereq_(106); var Transaction = _dereq_(127); var warning = _dereq_(187); function warnNoop(publicInstance, callerName) { if ("development" !== 'production') { var constructor = publicInstance.constructor; "development" !== 'production' ? warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * 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 () { /* :: transaction: Transaction; */ 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; }; /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ ReactServerUpdateQueue.prototype.enqueueCallback = function enqueueCallback(publicInstance, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueCallback(publicInstance, callback, callerName); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueForceUpdate(publicInstance); } 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. * @internal */ ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState); } 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) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueSetState(publicInstance, partialState); } else { warnNoop(publicInstance, 'setState'); } }; return ReactServerUpdateQueue; }(); module.exports = ReactServerUpdateQueue; },{"106":106,"127":127,"187":187}],101:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactStateSetters */ 'use strict'; var ReactStateSetters = { /** * Returns a function that calls the provided function, and uses the result * of that to set the component's state. * * @param {ReactCompositeComponent} component * @param {function} funcReturningState Returned callback uses this to * determine how to update state. * @return {function} callback that when invoked uses funcReturningState to * determined the object literal to setState. */ createStateSetter: function (component, funcReturningState) { return function (a, b, c, d, e, f) { var partialState = funcReturningState.call(component, a, b, c, d, e, f); if (partialState) { component.setState(partialState); } }; }, /** * Returns a single-argument callback that can be used to update a single * key in the component's state. * * Note: this is memoized function, which makes it inexpensive to call. * * @param {ReactCompositeComponent} component * @param {string} key The key in the state that you should update. * @return {function} callback of 1 argument which calls setState() with * the provided keyName and callback argument. */ createStateKeySetter: function (component, key) { // Memoize the setters. var cache = component.__keySetters || (component.__keySetters = {}); return cache[key] || (cache[key] = createStateKeySetter(component, key)); } }; function createStateKeySetter(component, key) { // Partial state is allocated outside of the function closure so it can be // reused with every call, avoiding memory allocation when this function // is called. var partialState = {}; return function stateKeySetter(value) { partialState[key] = value; component.setState(partialState); }; } ReactStateSetters.Mixin = { /** * Returns a function that calls the provided function, and uses the result * of that to set the component's state. * * For example, these statements are equivalent: * * this.setState({x: 1}); * this.createStateSetter(function(xValue) { * return {x: xValue}; * })(1); * * @param {function} funcReturningState Returned callback uses this to * determine how to update state. * @return {function} callback that when invoked uses funcReturningState to * determined the object literal to setState. */ createStateSetter: function (funcReturningState) { return ReactStateSetters.createStateSetter(this, funcReturningState); }, /** * Returns a single-argument callback that can be used to update a single * key in the component's state. * * For example, these statements are equivalent: * * this.setState({x: 1}); * this.createStateKeySetter('x')(1); * * Note: this is memoized function, which makes it inexpensive to call. * * @param {string} key The key in the state that you should update. * @return {function} callback of 1 argument which calls setState() with * the provided keyName and callback argument. */ createStateKeySetter: function (key) { return ReactStateSetters.createStateKeySetter(this, key); } }; module.exports = ReactStateSetters; },{}],102:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTestUtils */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var EventConstants = _dereq_(16); var EventPluginHub = _dereq_(17); var EventPluginRegistry = _dereq_(18); var EventPropagators = _dereq_(20); var React = _dereq_(27); var ReactDefaultInjection = _dereq_(64); var ReactDOM = _dereq_(42); var ReactDOMComponentTree = _dereq_(46); var ReactElement = _dereq_(65); var ReactBrowserEventEmitter = _dereq_(28); var ReactCompositeComponent = _dereq_(40); var ReactInstanceMap = _dereq_(77); var ReactReconciler = _dereq_(95); var ReactUpdates = _dereq_(107); var SyntheticEvent = _dereq_(118); var emptyObject = _dereq_(171); var findDOMNode = _dereq_(136); var invariant = _dereq_(178); var topLevelTypes = EventConstants.topLevelTypes; function Event(suffix) {} /** * @class ReactTestUtils */ function findAllInRenderedTreeInternal(inst, test) { if (!inst || !inst.getPublicInstance) { return []; } var publicInst = inst.getPublicInstance(); var ret = test(publicInst) ? [publicInst] : []; var currentElement = inst._currentElement; if (ReactTestUtils.isDOMComponent(publicInst)) { var renderedChildren = inst._renderedChildren; var key; for (key in renderedChildren) { if (!renderedChildren.hasOwnProperty(key)) { continue; } ret = ret.concat(findAllInRenderedTreeInternal(renderedChildren[key], test)); } } else if (ReactElement.isValidElement(currentElement) && typeof currentElement.type === 'function') { ret = ret.concat(findAllInRenderedTreeInternal(inst._renderedComponent, test)); } return ret; } /** * Utilities for making it easy to test React components. * * See https://facebook.github.io/react/docs/test-utils.html * * Todo: Support the entire DOM.scry query syntax. For now, these simple * utilities will suffice for testing purposes. * @lends ReactTestUtils */ var ReactTestUtils = { renderIntoDocument: function (instance) { var div = document.createElement('div'); // None of our tests actually require attaching the container to the // DOM, and doing so creates a mess that we rely on test isolation to // clean up, so we're going to stop honoring the name of this method // (and probably rename it eventually) if no problems arise. // document.documentElement.appendChild(div); return ReactDOM.render(instance, div); }, isElement: function (element) { return ReactElement.isValidElement(element); }, isElementOfType: function (inst, convenienceConstructor) { return ReactElement.isValidElement(inst) && inst.type === convenienceConstructor; }, isDOMComponent: function (inst) { return !!(inst && inst.nodeType === 1 && inst.tagName); }, isDOMComponentElement: function (inst) { return !!(inst && ReactElement.isValidElement(inst) && !!inst.tagName); }, isCompositeComponent: function (inst) { if (ReactTestUtils.isDOMComponent(inst)) { // Accessing inst.setState warns; just return false as that'll be what // this returns when we have DOM nodes as refs directly return false; } return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function'; }, isCompositeComponentWithType: function (inst, type) { if (!ReactTestUtils.isCompositeComponent(inst)) { return false; } var internalInstance = ReactInstanceMap.get(inst); var constructor = internalInstance._currentElement.type; return constructor === type; }, isCompositeComponentElement: function (inst) { if (!ReactElement.isValidElement(inst)) { return false; } // We check the prototype of the type that will get mounted, not the // instance itself. This is a future proof way of duck typing. var prototype = inst.type.prototype; return typeof prototype.render === 'function' && typeof prototype.setState === 'function'; }, isCompositeComponentElementWithType: function (inst, type) { var internalInstance = ReactInstanceMap.get(inst); var constructor = internalInstance._currentElement.type; return !!(ReactTestUtils.isCompositeComponentElement(inst) && constructor === type); }, getRenderedChildOfCompositeComponent: function (inst) { if (!ReactTestUtils.isCompositeComponent(inst)) { return null; } var internalInstance = ReactInstanceMap.get(inst); return internalInstance._renderedComponent.getPublicInstance(); }, findAllInRenderedTree: function (inst, test) { if (!inst) { return []; } !ReactTestUtils.isCompositeComponent(inst) ? "development" !== 'production' ? invariant(false, 'findAllInRenderedTree(...): instance must be a composite component') : _prodInvariant('10') : void 0; return findAllInRenderedTreeInternal(ReactInstanceMap.get(inst), test); }, /** * Finds all instance of components in the rendered tree that are DOM * components with the class name matching `className`. * @return {array} an array of all the matches. */ scryRenderedDOMComponentsWithClass: function (root, classNames) { return ReactTestUtils.findAllInRenderedTree(root, function (inst) { if (ReactTestUtils.isDOMComponent(inst)) { var className = inst.className; if (typeof className !== 'string') { // SVG, probably. className = inst.getAttribute('class') || ''; } var classList = className.split(/\s+/); if (!Array.isArray(classNames)) { !(classNames !== undefined) ? "development" !== 'production' ? invariant(false, 'TestUtils.scryRenderedDOMComponentsWithClass expects a className as a second argument.') : _prodInvariant('11') : void 0; classNames = classNames.split(/\s+/); } return classNames.every(function (name) { return classList.indexOf(name) !== -1; }); } return false; }); }, /** * Like scryRenderedDOMComponentsWithClass but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithClass: function (root, className) { var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className); if (all.length !== 1) { throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className); } return all[0]; }, /** * Finds all instance of components in the rendered tree that are DOM * components with the tag name matching `tagName`. * @return {array} an array of all the matches. */ scryRenderedDOMComponentsWithTag: function (root, tagName) { return ReactTestUtils.findAllInRenderedTree(root, function (inst) { return ReactTestUtils.isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase(); }); }, /** * Like scryRenderedDOMComponentsWithTag but expects there to be one result, * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactDOMComponent} The one match. */ findRenderedDOMComponentWithTag: function (root, tagName) { var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName); if (all.length !== 1) { throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName); } return all[0]; }, /** * Finds all instances of components with type equal to `componentType`. * @return {array} an array of all the matches. */ scryRenderedComponentsWithType: function (root, componentType) { return ReactTestUtils.findAllInRenderedTree(root, function (inst) { return ReactTestUtils.isCompositeComponentWithType(inst, componentType); }); }, /** * Same as `scryRenderedComponentsWithType` but expects there to be one result * and returns that one result, or throws exception if there is any other * number of matches besides one. * @return {!ReactComponent} The one match. */ findRenderedComponentWithType: function (root, componentType) { var all = ReactTestUtils.scryRenderedComponentsWithType(root, componentType); if (all.length !== 1) { throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType); } return all[0]; }, /** * Pass a mocked component module to this method to augment it with * useful methods that allow it to be used as a dummy React component. * Instead of rendering as usual, the component will become a simple * <div> containing any provided children. * * @param {object} module the mock function object exported from a * module that defines the component to be mocked * @param {?string} mockTagName optional dummy root tag name to return * from render method (overrides * module.mockTagName if provided) * @return {object} the ReactTestUtils object (for chaining) */ mockComponent: function (module, mockTagName) { mockTagName = mockTagName || module.mockTagName || 'div'; module.prototype.render.mockImplementation(function () { return React.createElement(mockTagName, null, this.props.children); }); return this; }, /** * Simulates a top level event being dispatched from a raw event that occurred * on an `Element` node. * @param {Object} topLevelType A type from `EventConstants.topLevelTypes` * @param {!Element} node The dom to simulate an event occurring on. * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateNativeEventOnNode: function (topLevelType, node, fakeNativeEvent) { fakeNativeEvent.target = node; ReactBrowserEventEmitter.ReactEventListener.dispatchEvent(topLevelType, fakeNativeEvent); }, /** * Simulates a top level event being dispatched from a raw event that occurred * on the `ReactDOMComponent` `comp`. * @param {Object} topLevelType A type from `EventConstants.topLevelTypes`. * @param {!ReactDOMComponent} comp * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. */ simulateNativeEventOnDOMComponent: function (topLevelType, comp, fakeNativeEvent) { ReactTestUtils.simulateNativeEventOnNode(topLevelType, findDOMNode(comp), fakeNativeEvent); }, nativeTouchData: function (x, y) { return { touches: [{ pageX: x, pageY: y }] }; }, createRenderer: function () { return new ReactShallowRenderer(); }, Simulate: null, SimulateNative: {} }; /** * @class ReactShallowRenderer */ var ReactShallowRenderer = function () { this._instance = null; }; ReactShallowRenderer.prototype.getMountedInstance = function () { return this._instance ? this._instance._instance : null; }; var nextDebugID = 1; var NoopInternalComponent = function (element) { this._renderedOutput = element; this._currentElement = element; if ("development" !== 'production') { this._debugID = nextDebugID++; } }; NoopInternalComponent.prototype = { mountComponent: function () {}, receiveComponent: function (element) { this._renderedOutput = element; this._currentElement = element; }, getHostNode: function () { return undefined; }, unmountComponent: function () {}, getPublicInstance: function () { return null; } }; var ShallowComponentWrapper = function (element) { // TODO: Consolidate with instantiateReactComponent if ("development" !== 'production') { this._debugID = nextDebugID++; } this.construct(element); }; _assign(ShallowComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _constructComponent: ReactCompositeComponent.Mixin._constructComponentWithoutOwner, _instantiateReactComponent: function (element) { return new NoopInternalComponent(element); }, _replaceNodeWithMarkup: function () {}, _renderValidatedComponent: ReactCompositeComponent.Mixin._renderValidatedComponentWithoutOwnerOrContext }); ReactShallowRenderer.prototype.render = function (element, context) { // Ensure we've done the default injections. This might not be true in the // case of a simple test that only requires React and the TestUtils in // conjunction with an inline-requires transform. ReactDefaultInjection.inject(); !ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'ReactShallowRenderer render(): Invalid component element.%s', typeof element === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : '') : _prodInvariant('12', typeof element === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : '') : void 0; !(typeof element.type !== 'string') ? "development" !== 'production' ? invariant(false, 'ReactShallowRenderer render(): Shallow rendering works only with custom components, not primitives (%s). Instead of calling `.render(el)` and inspecting the rendered output, look at `el.props` directly instead.', element.type) : _prodInvariant('13', element.type) : void 0; if (!context) { context = emptyObject; } ReactUpdates.batchedUpdates(_batchedRender, this, element, context); return this.getRenderOutput(); }; function _batchedRender(renderer, element, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(true); renderer._render(element, transaction, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } ReactShallowRenderer.prototype.getRenderOutput = function () { return this._instance && this._instance._renderedComponent && this._instance._renderedComponent._renderedOutput || null; }; ReactShallowRenderer.prototype.unmount = function () { if (this._instance) { ReactReconciler.unmountComponent(this._instance, false); } }; ReactShallowRenderer.prototype._render = function (element, transaction, context) { if (this._instance) { ReactReconciler.receiveComponent(this._instance, element, transaction, context); } else { var instance = new ShallowComponentWrapper(element); ReactReconciler.mountComponent(instance, transaction, null, null, context, 0); this._instance = instance; } }; /** * Exports: * * - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.mouseMove(Element/ReactDOMComponent)` * - `ReactTestUtils.Simulate.change(Element/ReactDOMComponent)` * - ... (All keys from event plugin `eventTypes` objects) */ function makeSimulator(eventType) { return function (domComponentOrNode, eventData) { var node; !!React.isValidElement(domComponentOrNode) ? "development" !== 'production' ? invariant(false, 'TestUtils.Simulate expects a component instance and not a ReactElement.TestUtils.Simulate will not work if you are using shallow rendering.') : _prodInvariant('14') : void 0; if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { node = findDOMNode(domComponentOrNode); } else if (domComponentOrNode.tagName) { node = domComponentOrNode; } var dispatchConfig = EventPluginRegistry.eventNameDispatchConfigs[eventType]; var fakeNativeEvent = new Event(); fakeNativeEvent.target = node; fakeNativeEvent.type = eventType.toLowerCase(); // We don't use SyntheticEvent.getPooled in order to not have to worry about // properly destroying any properties assigned from `eventData` upon release var event = new SyntheticEvent(dispatchConfig, ReactDOMComponentTree.getInstanceFromNode(node), fakeNativeEvent, node); // Since we aren't using pooling, always persist the event. This will make // sure it's marked and won't warn when setting additional properties. event.persist(); _assign(event, eventData); if (dispatchConfig.phasedRegistrationNames) { EventPropagators.accumulateTwoPhaseDispatches(event); } else { EventPropagators.accumulateDirectDispatches(event); } ReactUpdates.batchedUpdates(function () { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(true); }); }; } function buildSimulators() { ReactTestUtils.Simulate = {}; var eventType; for (eventType in EventPluginRegistry.eventNameDispatchConfigs) { /** * @param {!Element|ReactDOMComponent} domComponentOrNode * @param {?object} eventData Fake event data to use in SyntheticEvent. */ ReactTestUtils.Simulate[eventType] = makeSimulator(eventType); } } // Rebuild ReactTestUtils.Simulate whenever event plugins are injected var oldInjectEventPluginOrder = EventPluginHub.injection.injectEventPluginOrder; EventPluginHub.injection.injectEventPluginOrder = function () { oldInjectEventPluginOrder.apply(this, arguments); buildSimulators(); }; var oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName; EventPluginHub.injection.injectEventPluginsByName = function () { oldInjectEventPlugins.apply(this, arguments); buildSimulators(); }; buildSimulators(); /** * Exports: * * - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)` * - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)` * - ... (All keys from `EventConstants.topLevelTypes`) * * Note: Top level event types are a subset of the entire set of handler types * (which include a broader set of "synthetic" events). For example, onDragDone * is a synthetic event. Except when testing an event plugin or React's event * handling code specifically, you probably want to use ReactTestUtils.Simulate * to dispatch synthetic events. */ function makeNativeSimulator(eventType) { return function (domComponentOrNode, nativeEventData) { var fakeNativeEvent = new Event(eventType); _assign(fakeNativeEvent, nativeEventData); if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { ReactTestUtils.simulateNativeEventOnDOMComponent(eventType, domComponentOrNode, fakeNativeEvent); } else if (domComponentOrNode.tagName) { // Will allow on actual dom nodes. ReactTestUtils.simulateNativeEventOnNode(eventType, domComponentOrNode, fakeNativeEvent); } }; } Object.keys(topLevelTypes).forEach(function (eventType) { // Event type is stored as 'topClick' - we transform that to 'click' var convenienceName = eventType.indexOf('top') === 0 ? eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType; /** * @param {!Element|ReactDOMComponent} domComponentOrNode * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent. */ ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(eventType); }); module.exports = ReactTestUtils; },{"107":107,"118":118,"136":136,"153":153,"16":16,"17":17,"171":171,"178":178,"18":18,"188":188,"20":20,"27":27,"28":28,"40":40,"42":42,"46":46,"64":64,"65":65,"77":77,"95":95}],103:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionChildMapping */ 'use strict'; var flattenChildren = _dereq_(137); var ReactTransitionChildMapping = { /** * Given `this.props.children`, return an object mapping key to child. Just * simple syntactic sugar around flattenChildren(). * * @param {*} children `this.props.children` * @param {number=} selfDebugID Optional debugID of the current internal instance. * @return {object} Mapping of key to child */ getChildMapping: function (children, selfDebugID) { if (!children) { return children; } if ("development" !== 'production') { return flattenChildren(children, selfDebugID); } return flattenChildren(children); }, /** * When you're adding or removing children some may be added or removed in the * same render pass. We want to show *both* since we want to simultaneously * animate elements in and out. This function takes a previous set of keys * and a new set of keys and merges them with its best guess of the correct * ordering. In the future we may expose some of the utilities in * ReactMultiChild to make this easy, but for now React itself does not * directly have this concept of the union of prevChildren and nextChildren * so we implement it here. * * @param {object} prev prev children as returned from * `ReactTransitionChildMapping.getChildMapping()`. * @param {object} next next children as returned from * `ReactTransitionChildMapping.getChildMapping()`. * @return {object} a key set that contains all keys in `prev` and all keys * in `next` in a reasonable order. */ mergeChildMappings: function (prev, next) { prev = prev || {}; next = next || {}; function getValueForKey(key) { if (next.hasOwnProperty(key)) { return next[key]; } else { return prev[key]; } } // For each key of `next`, the list of keys to insert before that key in // the combined list var nextKeysPending = {}; var pendingKeys = []; for (var prevKey in prev) { if (next.hasOwnProperty(prevKey)) { if (pendingKeys.length) { nextKeysPending[prevKey] = pendingKeys; pendingKeys = []; } } else { pendingKeys.push(prevKey); } } var i; var childMapping = {}; for (var nextKey in next) { if (nextKeysPending.hasOwnProperty(nextKey)) { for (i = 0; i < nextKeysPending[nextKey].length; i++) { var pendingNextKey = nextKeysPending[nextKey][i]; childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey); } } childMapping[nextKey] = getValueForKey(nextKey); } // Finally, add the keys which didn't appear before any key in `next` for (i = 0; i < pendingKeys.length; i++) { childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]); } return childMapping; } }; module.exports = ReactTransitionChildMapping; },{"137":137}],104:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ 'use strict'; var ExecutionEnvironment = _dereq_(164); var getVendorPrefixedEventName = _dereq_(147); var endEvents = []; function detectEvents() { var animEnd = getVendorPrefixedEventName('animationend'); var transEnd = getVendorPrefixedEventName('transitionend'); if (animEnd) { endEvents.push(animEnd); } if (transEnd) { endEvents.push(transEnd); } } if (ExecutionEnvironment.canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function (endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function (endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; module.exports = ReactTransitionEvents; },{"147":147,"164":164}],105:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionGroup */ 'use strict'; var _assign = _dereq_(188); var React = _dereq_(27); var ReactInstanceMap = _dereq_(77); var ReactTransitionChildMapping = _dereq_(103); var emptyFunction = _dereq_(170); /** * A basis for animations. When children are declaratively added or removed, * special lifecycle hooks are called. * See https://facebook.github.io/react/docs/animation.html#low-level-api-reacttransitiongroup */ var ReactTransitionGroup = React.createClass({ displayName: 'ReactTransitionGroup', propTypes: { component: React.PropTypes.any, childFactory: React.PropTypes.func }, getDefaultProps: function () { return { component: 'span', childFactory: emptyFunction.thatReturnsArgument }; }, getInitialState: function () { return { // TODO: can we get useful debug information to show at this point? children: ReactTransitionChildMapping.getChildMapping(this.props.children) }; }, componentWillMount: function () { this.currentlyTransitioningKeys = {}; this.keysToEnter = []; this.keysToLeave = []; }, componentDidMount: function () { var initialChildMapping = this.state.children; for (var key in initialChildMapping) { if (initialChildMapping[key]) { this.performAppear(key); } } }, componentWillReceiveProps: function (nextProps) { var nextChildMapping; if ("development" !== 'production') { nextChildMapping = ReactTransitionChildMapping.getChildMapping(nextProps.children, ReactInstanceMap.get(this)._debugID); } else { nextChildMapping = ReactTransitionChildMapping.getChildMapping(nextProps.children); } var prevChildMapping = this.state.children; this.setState({ children: ReactTransitionChildMapping.mergeChildMappings(prevChildMapping, nextChildMapping) }); var key; for (key in nextChildMapping) { var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key); if (nextChildMapping[key] && !hasPrev && !this.currentlyTransitioningKeys[key]) { this.keysToEnter.push(key); } } for (key in prevChildMapping) { var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key); if (prevChildMapping[key] && !hasNext && !this.currentlyTransitioningKeys[key]) { this.keysToLeave.push(key); } } // If we want to someday check for reordering, we could do it here. }, componentDidUpdate: function () { var keysToEnter = this.keysToEnter; this.keysToEnter = []; keysToEnter.forEach(this.performEnter); var keysToLeave = this.keysToLeave; this.keysToLeave = []; keysToLeave.forEach(this.performLeave); }, performAppear: function (key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillAppear) { component.componentWillAppear(this._handleDoneAppearing.bind(this, key)); } else { this._handleDoneAppearing(key); } }, _handleDoneAppearing: function (key) { var component = this.refs[key]; if (component.componentDidAppear) { component.componentDidAppear(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping; if ("development" !== 'production') { currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children, ReactInstanceMap.get(this)._debugID); } else { currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children); } if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) { // This was removed before it had fully appeared. Remove it. this.performLeave(key); } }, performEnter: function (key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillEnter) { component.componentWillEnter(this._handleDoneEntering.bind(this, key)); } else { this._handleDoneEntering(key); } }, _handleDoneEntering: function (key) { var component = this.refs[key]; if (component.componentDidEnter) { component.componentDidEnter(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping; if ("development" !== 'production') { currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children, ReactInstanceMap.get(this)._debugID); } else { currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children); } if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) { // This was removed before it had fully entered. Remove it. this.performLeave(key); } }, performLeave: function (key) { this.currentlyTransitioningKeys[key] = true; var component = this.refs[key]; if (component.componentWillLeave) { component.componentWillLeave(this._handleDoneLeaving.bind(this, key)); } else { // Note that this is somewhat dangerous b/c it calls setState() // again, effectively mutating the component before all the work // is done. this._handleDoneLeaving(key); } }, _handleDoneLeaving: function (key) { var component = this.refs[key]; if (component.componentDidLeave) { component.componentDidLeave(); } delete this.currentlyTransitioningKeys[key]; var currentChildMapping; if ("development" !== 'production') { currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children, ReactInstanceMap.get(this)._debugID); } else { currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children); } if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) { // This entered again before it fully left. Add it again. this.performEnter(key); } else { this.setState(function (state) { var newChildren = _assign({}, state.children); delete newChildren[key]; return { children: newChildren }; }); } }, render: function () { // TODO: we could get rid of the need for the wrapper node // by cloning a single child var childrenToRender = []; for (var key in this.state.children) { var child = this.state.children[key]; if (child) { // You may need to apply reactive updates to a child as it is leaving. // The normal React way to do it won't work since the child will have // already been removed. In case you need this behavior you can provide // a childFactory function to wrap every child, even the ones that are // leaving. childrenToRender.push(React.cloneElement(this.props.childFactory(child), { ref: key, key: key })); } } // Do not forward ReactTransitionGroup props to primitive DOM nodes var props = _assign({}, this.props); delete props.transitionLeave; delete props.transitionName; delete props.transitionAppear; delete props.transitionEnter; delete props.childFactory; delete props.transitionLeaveTimeout; delete props.transitionEnterTimeout; delete props.transitionAppearTimeout; delete props.component; return React.createElement(this.props.component, props, childrenToRender); } }); module.exports = ReactTransitionGroup; },{"103":103,"170":170,"188":188,"27":27,"77":77}],106:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdateQueue */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactCurrentOwner = _dereq_(41); var ReactInstanceMap = _dereq_(77); var ReactInstrumentation = _dereq_(78); var ReactUpdates = _dereq_(107); var invariant = _dereq_(178); var warning = _dereq_(187); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function formatUnexpectedArgument(arg) { var type = typeof arg; if (type !== 'object') { return type; } var displayName = arg.constructor && arg.constructor.name || type; var keys = Object.keys(arg); if (keys.length > 0 && keys.length < 20) { return displayName + ' (keys: ' + keys.join(', ') + ')'; } return displayName; } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if ("development" !== 'production') { var ctor = publicInstance.constructor; // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. "development" !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, ctor && (ctor.displayName || ctor.name) || 'ReactClass') : void 0; } return null; } if ("development" !== 'production') { "development" !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if ("development" !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @param {string} callerName Name of the calling function in the public API. * @internal */ enqueueCallback: function (publicInstance, callback, callerName) { ReactUpdateQueue.validateCallback(callback, callerName); var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { if ("development" !== 'production') { ReactInstrumentation.debugTool.onSetState(); "development" !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0; } var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, enqueueElementInternal: function (internalInstance, nextElement, nextContext) { internalInstance._pendingElement = nextElement; // TODO: introduce _pendingContext instead of setting it directly. internalInstance._context = nextContext; enqueueUpdate(internalInstance); }, validateCallback: function (callback, callerName) { !(!callback || typeof callback === 'function') ? "development" !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : _prodInvariant('122', callerName, formatUnexpectedArgument(callback)) : void 0; } }; module.exports = ReactUpdateQueue; },{"107":107,"153":153,"178":178,"187":187,"41":41,"77":77,"78":78}],107:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var CallbackQueue = _dereq_(5); var PooledClass = _dereq_(26); var ReactFeatureFlags = _dereq_(71); var ReactReconciler = _dereq_(95); var Transaction = _dereq_(127); var invariant = _dereq_(178); var dirtyComponents = []; var updateBatchNumber = 0; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */true); } _assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? "development" !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', 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]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.props === component._renderedComponent._currentElement) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber); if (markerName) { console.timeEnd(markerName); } if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? "development" !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; },{"127":127,"153":153,"178":178,"188":188,"26":26,"5":5,"71":71,"95":95}],108:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactVersion */ 'use strict'; module.exports = '15.3.1'; },{}],109:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactWithAddons */ 'use strict'; var LinkedStateMixin = _dereq_(24); var React = _dereq_(27); var ReactComponentWithPureRenderMixin = _dereq_(39); var ReactCSSTransitionGroup = _dereq_(29); var ReactFragment = _dereq_(72); var ReactTransitionGroup = _dereq_(105); var shallowCompare = _dereq_(157); var update = _dereq_(160); React.addons = { CSSTransitionGroup: ReactCSSTransitionGroup, LinkedStateMixin: LinkedStateMixin, PureRenderMixin: ReactComponentWithPureRenderMixin, TransitionGroup: ReactTransitionGroup, createFragment: ReactFragment.create, shallowCompare: shallowCompare, update: update }; if ("development" !== 'production') { React.addons.Perf = _dereq_(88); React.addons.TestUtils = _dereq_(102); } module.exports = React; },{"102":102,"105":105,"157":157,"160":160,"24":24,"27":27,"29":29,"39":39,"72":72,"88":88}],110:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactWithAddonsUMDEntry */ 'use strict'; var _assign = _dereq_(188); var ReactDOM = _dereq_(42); var ReactDOMServer = _dereq_(57); var ReactWithAddons = _dereq_(109); // `version` will be added here by ReactIsomorphic. var ReactWithAddonsUMDEntry = _assign({ __SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOM, __SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactDOMServer }, ReactWithAddons); module.exports = ReactWithAddonsUMDEntry; },{"109":109,"188":188,"42":42,"57":57}],111:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ 'use strict'; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', 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]; } }); module.exports = SVGDOMPropertyConfig; },{}],112:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ 'use strict'; var EventConstants = _dereq_(16); var EventPropagators = _dereq_(20); var ExecutionEnvironment = _dereq_(164); var ReactDOMComponentTree = _dereq_(46); var ReactInputSelection = _dereq_(76); var SyntheticEvent = _dereq_(118); var getActiveElement = _dereq_(173); var isTextInputElement = _dereq_(150); var keyOf = _dereq_(182); var shallowEqual = _dereq_(186); var topLevelTypes = EventConstants.topLevelTypes; var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({ onSelect: null }), captured: keyOf({ onSelectCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange] } }; var activeElement = null; var activeElementInst = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. See #3639. var hasListener = false; var ON_SELECT_KEY = keyOf({ onSelect: null }); /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement = targetNode; activeElementInst = targetInst; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementInst = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case topLevelTypes.topSelectionChange: if (skipSelectionChangeEvent) { break; } // falls through case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (inst, registrationName, listener) { if (registrationName === ON_SELECT_KEY) { hasListener = true; } } }; module.exports = SelectEventPlugin; },{"118":118,"150":150,"16":16,"164":164,"173":173,"182":182,"186":186,"20":20,"46":46,"76":76}],113:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ 'use strict'; var _prodInvariant = _dereq_(153); var EventConstants = _dereq_(16); var EventListener = _dereq_(163); var EventPropagators = _dereq_(20); var ReactDOMComponentTree = _dereq_(46); var SyntheticAnimationEvent = _dereq_(114); var SyntheticClipboardEvent = _dereq_(115); var SyntheticEvent = _dereq_(118); var SyntheticFocusEvent = _dereq_(119); var SyntheticKeyboardEvent = _dereq_(121); var SyntheticMouseEvent = _dereq_(122); var SyntheticDragEvent = _dereq_(117); var SyntheticTouchEvent = _dereq_(123); var SyntheticTransitionEvent = _dereq_(124); var SyntheticUIEvent = _dereq_(125); var SyntheticWheelEvent = _dereq_(126); var emptyFunction = _dereq_(170); var getEventCharCode = _dereq_(139); var invariant = _dereq_(178); var keyOf = _dereq_(182); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { abort: { phasedRegistrationNames: { bubbled: keyOf({ onAbort: true }), captured: keyOf({ onAbortCapture: true }) } }, animationEnd: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationEnd: true }), captured: keyOf({ onAnimationEndCapture: true }) } }, animationIteration: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationIteration: true }), captured: keyOf({ onAnimationIterationCapture: true }) } }, animationStart: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationStart: true }), captured: keyOf({ onAnimationStartCapture: true }) } }, blur: { phasedRegistrationNames: { bubbled: keyOf({ onBlur: true }), captured: keyOf({ onBlurCapture: true }) } }, canPlay: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlay: true }), captured: keyOf({ onCanPlayCapture: true }) } }, canPlayThrough: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlayThrough: true }), captured: keyOf({ onCanPlayThroughCapture: true }) } }, click: { phasedRegistrationNames: { bubbled: keyOf({ onClick: true }), captured: keyOf({ onClickCapture: true }) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({ onContextMenu: true }), captured: keyOf({ onContextMenuCapture: true }) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({ onCopy: true }), captured: keyOf({ onCopyCapture: true }) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({ onCut: true }), captured: keyOf({ onCutCapture: true }) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({ onDoubleClick: true }), captured: keyOf({ onDoubleClickCapture: true }) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({ onDrag: true }), captured: keyOf({ onDragCapture: true }) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnd: true }), captured: keyOf({ onDragEndCapture: true }) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnter: true }), captured: keyOf({ onDragEnterCapture: true }) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({ onDragExit: true }), captured: keyOf({ onDragExitCapture: true }) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({ onDragLeave: true }), captured: keyOf({ onDragLeaveCapture: true }) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({ onDragOver: true }), captured: keyOf({ onDragOverCapture: true }) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({ onDragStart: true }), captured: keyOf({ onDragStartCapture: true }) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({ onDrop: true }), captured: keyOf({ onDropCapture: true }) } }, durationChange: { phasedRegistrationNames: { bubbled: keyOf({ onDurationChange: true }), captured: keyOf({ onDurationChangeCapture: true }) } }, emptied: { phasedRegistrationNames: { bubbled: keyOf({ onEmptied: true }), captured: keyOf({ onEmptiedCapture: true }) } }, encrypted: { phasedRegistrationNames: { bubbled: keyOf({ onEncrypted: true }), captured: keyOf({ onEncryptedCapture: true }) } }, ended: { phasedRegistrationNames: { bubbled: keyOf({ onEnded: true }), captured: keyOf({ onEndedCapture: true }) } }, error: { phasedRegistrationNames: { bubbled: keyOf({ onError: true }), captured: keyOf({ onErrorCapture: true }) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({ onFocus: true }), captured: keyOf({ onFocusCapture: true }) } }, input: { phasedRegistrationNames: { bubbled: keyOf({ onInput: true }), captured: keyOf({ onInputCapture: true }) } }, invalid: { phasedRegistrationNames: { bubbled: keyOf({ onInvalid: true }), captured: keyOf({ onInvalidCapture: true }) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({ onKeyDown: true }), captured: keyOf({ onKeyDownCapture: true }) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({ onKeyPress: true }), captured: keyOf({ onKeyPressCapture: true }) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({ onKeyUp: true }), captured: keyOf({ onKeyUpCapture: true }) } }, load: { phasedRegistrationNames: { bubbled: keyOf({ onLoad: true }), captured: keyOf({ onLoadCapture: true }) } }, loadedData: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedData: true }), captured: keyOf({ onLoadedDataCapture: true }) } }, loadedMetadata: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedMetadata: true }), captured: keyOf({ onLoadedMetadataCapture: true }) } }, loadStart: { phasedRegistrationNames: { bubbled: keyOf({ onLoadStart: true }), captured: keyOf({ onLoadStartCapture: true }) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({ onMouseDown: true }), captured: keyOf({ onMouseDownCapture: true }) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({ onMouseMove: true }), captured: keyOf({ onMouseMoveCapture: true }) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOut: true }), captured: keyOf({ onMouseOutCapture: true }) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOver: true }), captured: keyOf({ onMouseOverCapture: true }) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({ onMouseUp: true }), captured: keyOf({ onMouseUpCapture: true }) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({ onPaste: true }), captured: keyOf({ onPasteCapture: true }) } }, pause: { phasedRegistrationNames: { bubbled: keyOf({ onPause: true }), captured: keyOf({ onPauseCapture: true }) } }, play: { phasedRegistrationNames: { bubbled: keyOf({ onPlay: true }), captured: keyOf({ onPlayCapture: true }) } }, playing: { phasedRegistrationNames: { bubbled: keyOf({ onPlaying: true }), captured: keyOf({ onPlayingCapture: true }) } }, progress: { phasedRegistrationNames: { bubbled: keyOf({ onProgress: true }), captured: keyOf({ onProgressCapture: true }) } }, rateChange: { phasedRegistrationNames: { bubbled: keyOf({ onRateChange: true }), captured: keyOf({ onRateChangeCapture: true }) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({ onReset: true }), captured: keyOf({ onResetCapture: true }) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({ onScroll: true }), captured: keyOf({ onScrollCapture: true }) } }, seeked: { phasedRegistrationNames: { bubbled: keyOf({ onSeeked: true }), captured: keyOf({ onSeekedCapture: true }) } }, seeking: { phasedRegistrationNames: { bubbled: keyOf({ onSeeking: true }), captured: keyOf({ onSeekingCapture: true }) } }, stalled: { phasedRegistrationNames: { bubbled: keyOf({ onStalled: true }), captured: keyOf({ onStalledCapture: true }) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({ onSubmit: true }), captured: keyOf({ onSubmitCapture: true }) } }, suspend: { phasedRegistrationNames: { bubbled: keyOf({ onSuspend: true }), captured: keyOf({ onSuspendCapture: true }) } }, timeUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onTimeUpdate: true }), captured: keyOf({ onTimeUpdateCapture: true }) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({ onTouchCancel: true }), captured: keyOf({ onTouchCancelCapture: true }) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTouchEnd: true }), captured: keyOf({ onTouchEndCapture: true }) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({ onTouchMove: true }), captured: keyOf({ onTouchMoveCapture: true }) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({ onTouchStart: true }), captured: keyOf({ onTouchStartCapture: true }) } }, transitionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTransitionEnd: true }), captured: keyOf({ onTransitionEndCapture: true }) } }, volumeChange: { phasedRegistrationNames: { bubbled: keyOf({ onVolumeChange: true }), captured: keyOf({ onVolumeChangeCapture: true }) } }, waiting: { phasedRegistrationNames: { bubbled: keyOf({ onWaiting: true }), captured: keyOf({ onWaitingCapture: true }) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({ onWheel: true }), captured: keyOf({ onWheelCapture: true }) } } }; var topLevelEventsToDispatchConfig = { topAbort: eventTypes.abort, topAnimationEnd: eventTypes.animationEnd, topAnimationIteration: eventTypes.animationIteration, topAnimationStart: eventTypes.animationStart, topBlur: eventTypes.blur, topCanPlay: eventTypes.canPlay, topCanPlayThrough: eventTypes.canPlayThrough, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topDurationChange: eventTypes.durationChange, topEmptied: eventTypes.emptied, topEncrypted: eventTypes.encrypted, topEnded: eventTypes.ended, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topInvalid: eventTypes.invalid, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topLoadedData: eventTypes.loadedData, topLoadedMetadata: eventTypes.loadedMetadata, topLoadStart: eventTypes.loadStart, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topPause: eventTypes.pause, topPlay: eventTypes.play, topPlaying: eventTypes.playing, topProgress: eventTypes.progress, topRateChange: eventTypes.rateChange, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSeeked: eventTypes.seeked, topSeeking: eventTypes.seeking, topStalled: eventTypes.stalled, topSubmit: eventTypes.submit, topSuspend: eventTypes.suspend, topTimeUpdate: eventTypes.timeUpdate, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topTransitionEnd: eventTypes.transitionEnd, topVolumeChange: eventTypes.volumeChange, topWaiting: eventTypes.waiting, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[type].dependencies = [type]; } var ON_CLICK_KEY = keyOf({ onClick: null }); var onClickListeners = {}; function getDictionaryKey(inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; } var SimpleEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topAbort: case topLevelTypes.topCanPlay: case topLevelTypes.topCanPlayThrough: case topLevelTypes.topDurationChange: case topLevelTypes.topEmptied: case topLevelTypes.topEncrypted: case topLevelTypes.topEnded: case topLevelTypes.topError: case topLevelTypes.topInput: case topLevelTypes.topInvalid: case topLevelTypes.topLoad: case topLevelTypes.topLoadedData: case topLevelTypes.topLoadedMetadata: case topLevelTypes.topLoadStart: case topLevelTypes.topPause: case topLevelTypes.topPlay: case topLevelTypes.topPlaying: case topLevelTypes.topProgress: case topLevelTypes.topRateChange: case topLevelTypes.topReset: case topLevelTypes.topSeeked: case topLevelTypes.topSeeking: case topLevelTypes.topStalled: case topLevelTypes.topSubmit: case topLevelTypes.topSuspend: case topLevelTypes.topTimeUpdate: case topLevelTypes.topVolumeChange: case topLevelTypes.topWaiting: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topAnimationEnd: case topLevelTypes.topAnimationIteration: case topLevelTypes.topAnimationStart: EventConstructor = SyntheticAnimationEvent; break; case topLevelTypes.topTransitionEnd: EventConstructor = SyntheticTransitionEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? "development" !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : _prodInvariant('86', topLevelType) : void 0; var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (inst, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. if (registrationName === ON_CLICK_KEY) { var key = getDictionaryKey(inst); var node = ReactDOMComponentTree.getNodeFromInstance(inst); if (!onClickListeners[key]) { onClickListeners[key] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (inst, registrationName) { if (registrationName === ON_CLICK_KEY) { var key = getDictionaryKey(inst); onClickListeners[key].remove(); delete onClickListeners[key]; } } }; module.exports = SimpleEventPlugin; },{"114":114,"115":115,"117":117,"118":118,"119":119,"121":121,"122":122,"123":123,"124":124,"125":125,"126":126,"139":139,"153":153,"16":16,"163":163,"170":170,"178":178,"182":182,"20":20,"46":46}],114:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticAnimationEvent */ 'use strict'; var SyntheticEvent = _dereq_(118); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface); module.exports = SyntheticAnimationEvent; },{"118":118}],115:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent */ 'use strict'; var SyntheticEvent = _dereq_(118); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"118":118}],116:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent */ 'use strict'; var SyntheticEvent = _dereq_(118); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; },{"118":118}],117:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent */ 'use strict'; var SyntheticMouseEvent = _dereq_(122); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"122":122}],118:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent */ 'use strict'; var _assign = _dereq_(188); var PooledClass = _dereq_(26); var emptyFunction = _dereq_(170); var warning = _dereq_(187); var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { if ("development" !== 'production') { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } if ("development" !== 'production') { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== 'unknown') { // eslint-disable-line valid-typeof // 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.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { if ("development" !== 'production') { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } else { this[propName] = null; } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } if ("development" !== 'production') { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)); } } }); SyntheticEvent.Interface = EventInterface; if ("development" !== 'production') { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { "development" !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; "development" !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } },{"170":170,"187":187,"188":188,"26":26}],119:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(125); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"125":125}],120:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent */ 'use strict'; var SyntheticEvent = _dereq_(118); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; },{"118":118}],121:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(125); var getEventCharCode = _dereq_(139); var getEventKey = _dereq_(140); var getEventModifierState = _dereq_(141); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"125":125,"139":139,"140":140,"141":141}],122:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(125); var ViewportMetrics = _dereq_(128); var getEventModifierState = _dereq_(141); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"125":125,"128":128,"141":141}],123:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent */ 'use strict'; var SyntheticUIEvent = _dereq_(125); var getEventModifierState = _dereq_(141); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"125":125,"141":141}],124:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTransitionEvent */ 'use strict'; var SyntheticEvent = _dereq_(118); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface); module.exports = SyntheticTransitionEvent; },{"118":118}],125:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent */ 'use strict'; var SyntheticEvent = _dereq_(118); var getEventTarget = _dereq_(142); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"118":118,"142":142}],126:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent */ 'use strict'; var SyntheticMouseEvent = _dereq_(122); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"122":122}],127:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ 'use strict'; var _prodInvariant = _dereq_(153); var invariant = _dereq_(178); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occurred. */ OBSERVED_ERROR: {} }; module.exports = Transaction; },{"153":153,"178":178}],128:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{}],129:[function(_dereq_,module,exports){ /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule accumulateInto * */ 'use strict'; var _prodInvariant = _dereq_(153); var invariant = _dereq_(178); /** * 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) ? "development" !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : 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]; } module.exports = accumulateInto; },{"153":153,"178":178}],130:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 * */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { var n = Math.min(i + 4096, m); for (; i < n; i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; },{}],131:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule canDefineProperty */ 'use strict'; var canDefineProperty = false; if ("development" !== 'production') { try { Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; },{}],132:[function(_dereq_,module,exports){ (function (process){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule checkReactTypeSpec */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactPropTypeLocationNames = _dereq_(89); var ReactPropTypesSecret = _dereq_(92); var invariant = _dereq_(178); var warning = _dereq_(187); var ReactComponentTreeHook; 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 = _dereq_(38); } var loggedTypeFailures = {}; /** * 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 {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { 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. !(typeof typeSpecs[typeSpecName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } "development" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if ("development" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = _dereq_(38); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } "development" !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; }).call(this,undefined) },{"153":153,"178":178,"187":187,"38":38,"89":89,"92":92}],133:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createMicrosoftUnsafeLocalFunction */ /* globals MSApp */ 'use strict'; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; module.exports = createMicrosoftUnsafeLocalFunction; },{}],134:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue */ 'use strict'; var CSSProperty = _dereq_(3); var warning = _dereq_(187); var isUnitlessNumber = CSSProperty.isUnitlessNumber; var styleWarnings = {}; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { if ("development" !== 'production') { // Allow '0' to pass through without warning. 0 is already special and // doesn't require units, so we don't need to warn about it. if (component && value !== '0') { var owner = component._currentElement._owner; var ownerName = owner ? owner.getName() : null; if (ownerName && !styleWarnings[ownerName]) { styleWarnings[ownerName] = {}; } var warned = false; if (ownerName) { var warnings = styleWarnings[ownerName]; warned = warnings[name]; if (!warned) { warnings[name] = true; } } if (!warned) { "development" !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0; } } } value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; },{"187":187,"3":3}],135:[function(_dereq_,module,exports){ /** * 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 */ 'use strict'; // 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); } module.exports = escapeTextContentForBrowser; },{}],136:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule findDOMNode */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactCurrentOwner = _dereq_(41); var ReactDOMComponentTree = _dereq_(46); var ReactInstanceMap = _dereq_(77); var getHostComponentFromComposite = _dereq_(143); var invariant = _dereq_(178); var warning = _dereq_(187); /** * Returns the DOM node rendered by this element. * * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode * * @param {ReactComponent|DOMElement} componentOrElement * @return {?DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if ("development" !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getHostComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { !false ? "development" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44') : void 0; } else { !false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0; } } module.exports = findDOMNode; },{"143":143,"153":153,"178":178,"187":187,"41":41,"46":46,"77":77}],137:[function(_dereq_,module,exports){ (function (process){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren * */ 'use strict'; var KeyEscapeUtils = _dereq_(23); var traverseAllChildren = _dereq_(159); var warning = _dereq_(187); var ReactComponentTreeHook; 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 = _dereq_(38); } /** * @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 ("development" !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = _dereq_(38); } if (!keyUnique) { "development" !== 'production' ? warning(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.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (keyUnique && child != null) { result[name] = child; } } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children, selfDebugID) { if (children == null) { return children; } var result = {}; if ("development" !== 'production') { traverseAllChildren(children, function (traverseContext, child, name) { return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID); }, result); } else { traverseAllChildren(children, flattenSingleChildIntoContext, result); } return result; } module.exports = flattenChildren; }).call(this,undefined) },{"159":159,"187":187,"23":23,"38":38}],138:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated * */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } module.exports = forEachAccumulated; },{}],139:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; },{}],140:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey */ 'use strict'; var getEventCharCode = _dereq_(139); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; },{"139":139}],141:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; },{}],142:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventTarget */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; },{}],143:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getHostComponentFromComposite */ 'use strict'; var ReactNodeTypes = _dereq_(85); function getHostComponentFromComposite(inst) { var type; while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) { inst = inst._renderedComponent; } if (type === ReactNodeTypes.HOST) { return inst._renderedComponent; } else if (type === ReactNodeTypes.EMPTY) { return null; } } module.exports = getHostComponentFromComposite; },{"85":85}],144:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getIteratorFn * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; },{}],145:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNodeForCharacterOffset */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; },{}],146:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ 'use strict'; var ExecutionEnvironment = _dereq_(164); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; },{"164":164}],147:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getVendorPrefixedEventName */ 'use strict'; var ExecutionEnvironment = _dereq_(164); /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment.canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; } module.exports = getVendorPrefixedEventName; },{"164":164}],148:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var ReactCompositeComponent = _dereq_(40); var ReactEmptyComponent = _dereq_(67); var ReactHostComponent = _dereq_(73); var invariant = _dereq_(178); var warning = _dereq_(187); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; _assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } var nextDebugID = 1; /** * 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.create(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : _prodInvariant('130', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : void 0; // Special case string values if (typeof element.type === 'string') { instance = ReactHostComponent.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.createInstanceForText(node); } else { !false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0; } if ("development" !== 'production') { "development" !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0; } // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if ("development" !== 'production') { instance._debugID = shouldHaveDebugID ? nextDebugID++ : 0; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if ("development" !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; },{"153":153,"178":178,"187":187,"188":188,"40":40,"67":67,"73":73}],149:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ 'use strict'; var ExecutionEnvironment = _dereq_(164); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; },{"164":164}],150:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement * */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); if (nodeName === 'input') { return !!supportedInputTypes[elem.type]; } if (nodeName === 'textarea') { return true; } return false; } module.exports = isTextInputElement; },{}],151:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule onlyChild */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactElement = _dereq_(65); var invariant = _dereq_(178); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? "development" !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0; return children; } module.exports = onlyChild; },{"153":153,"178":178,"65":65}],152:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule quoteAttributeValueForBrowser */ 'use strict'; var escapeTextContentForBrowser = _dereq_(135); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; },{"135":135}],153:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule reactProdInvariant * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; },{}],154:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule renderSubtreeIntoContainer */ 'use strict'; var ReactMount = _dereq_(82); module.exports = ReactMount.renderSubtreeIntoContainer; },{"82":82}],155:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ 'use strict'; var ExecutionEnvironment = _dereq_(164); var DOMNamespaces = _dereq_(9); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; var createMicrosoftUnsafeLocalFunction = _dereq_(133); // SVG temp container for IE lacking innerHTML var reusableSVGContainer; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { // 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.svg && !('innerHTML' in node)) { reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>'; var newNodes = reusableSVGContainer.firstChild.childNodes; for (var i = 0; i < newNodes.length; i++) { node.appendChild(newNodes[i]); } } else { node.innerHTML = html; } }); if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } testElement = null; } module.exports = setInnerHTML; },{"133":133,"164":164,"9":9}],156:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setTextContent */ 'use strict'; var ExecutionEnvironment = _dereq_(164); var escapeTextContentForBrowser = _dereq_(135); var setInnerHTML = _dereq_(155); /** * 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 === 3) { firstChild.nodeValue = text; return; } } node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; },{"135":135,"155":155,"164":164}],157:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowCompare */ 'use strict'; var shallowEqual = _dereq_(186); /** * Does a shallow comparison for props and state. * See ReactComponentWithPureRenderMixin * See also https://facebook.github.io/react/docs/shallow-compare.html */ function shallowCompare(instance, nextProps, nextState) { return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState); } module.exports = shallowCompare; },{"186":186}],158:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } } module.exports = shouldUpdateReactComponent; },{}],159:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ 'use strict'; var _prodInvariant = _dereq_(153); var ReactCurrentOwner = _dereq_(41); var ReactElement = _dereq_(65); var getIteratorFn = _dereq_(144); var invariant = _dereq_(178); var KeyEscapeUtils = _dereq_(23); var warning = _dereq_(187); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if ("development" !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } "development" !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if ("development" !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); !false ? "development" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; },{"144":144,"153":153,"178":178,"187":187,"23":23,"41":41,"65":65}],160:[function(_dereq_,module,exports){ /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule update */ /* global hasOwnProperty:true */ 'use strict'; var _prodInvariant = _dereq_(153), _assign = _dereq_(188); var keyOf = _dereq_(182); var invariant = _dereq_(178); var hasOwnProperty = {}.hasOwnProperty; function shallowCopy(x) { if (Array.isArray(x)) { return x.concat(); } else if (x && typeof x === 'object') { return _assign(new x.constructor(), x); } else { return x; } } var COMMAND_PUSH = keyOf({ $push: null }); var COMMAND_UNSHIFT = keyOf({ $unshift: null }); var COMMAND_SPLICE = keyOf({ $splice: null }); var COMMAND_SET = keyOf({ $set: null }); var COMMAND_MERGE = keyOf({ $merge: null }); var COMMAND_APPLY = keyOf({ $apply: null }); var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY]; var ALL_COMMANDS_SET = {}; ALL_COMMANDS_LIST.forEach(function (command) { ALL_COMMANDS_SET[command] = true; }); function invariantArrayCase(value, spec, command) { !Array.isArray(value) ? "development" !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : _prodInvariant('1', command, value) : void 0; var specValue = spec[command]; !Array.isArray(specValue) ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. Did you forget to wrap your parameter in an array?', command, specValue) : _prodInvariant('2', command, specValue) : void 0; } /** * Returns a updated shallow copy of an object without mutating the original. * See https://facebook.github.io/react/docs/update.html for details. */ function update(value, spec) { !(typeof spec === 'object') ? "development" !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : _prodInvariant('3', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : void 0; if (hasOwnProperty.call(spec, COMMAND_SET)) { !(Object.keys(spec).length === 1) ? "development" !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : _prodInvariant('4', COMMAND_SET) : void 0; return spec[COMMAND_SET]; } var nextValue = shallowCopy(value); if (hasOwnProperty.call(spec, COMMAND_MERGE)) { var mergeObj = spec[COMMAND_MERGE]; !(mergeObj && typeof mergeObj === 'object') ? "development" !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : _prodInvariant('5', COMMAND_MERGE, mergeObj) : void 0; !(nextValue && typeof nextValue === 'object') ? "development" !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : _prodInvariant('6', COMMAND_MERGE, nextValue) : void 0; _assign(nextValue, spec[COMMAND_MERGE]); } if (hasOwnProperty.call(spec, COMMAND_PUSH)) { invariantArrayCase(value, spec, COMMAND_PUSH); spec[COMMAND_PUSH].forEach(function (item) { nextValue.push(item); }); } if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) { invariantArrayCase(value, spec, COMMAND_UNSHIFT); spec[COMMAND_UNSHIFT].forEach(function (item) { nextValue.unshift(item); }); } if (hasOwnProperty.call(spec, COMMAND_SPLICE)) { !Array.isArray(value) ? "development" !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : _prodInvariant('7', COMMAND_SPLICE, value) : void 0; !Array.isArray(spec[COMMAND_SPLICE]) ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0; spec[COMMAND_SPLICE].forEach(function (args) { !Array.isArray(args) ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0; nextValue.splice.apply(nextValue, args); }); } if (hasOwnProperty.call(spec, COMMAND_APPLY)) { !(typeof spec[COMMAND_APPLY] === 'function') ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : _prodInvariant('9', COMMAND_APPLY, spec[COMMAND_APPLY]) : void 0; nextValue = spec[COMMAND_APPLY](nextValue); } for (var k in spec) { if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) { nextValue[k] = update(value[k], spec[k]); } } return nextValue; } module.exports = update; },{"153":153,"178":178,"182":182,"188":188}],161:[function(_dereq_,module,exports){ /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule validateDOMNesting */ 'use strict'; var _assign = _dereq_(188); var emptyFunction = _dereq_(170); var warning = _dereq_(187); var validateDOMNesting = emptyFunction; if ("development" !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; var tagDisplayName = childTag; if (childTag !== '#text') { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } "development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>. ' + 'See %s.%s', tagDisplayName, ancestorTag, ownerInfo, info) : void 0; } else { "development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0; } } }; validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; },{"170":170,"187":187,"188":188}],162:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var invariant = _dereq_(178); /** * The CSSCore module specifies the API (and implements most of the methods) * that should be used when dealing with the display of elements (via their * CSS classes and visibility on screen. It is an API focused on mutating the * display and not reading it as no logical state should be encoded in the * display of elements. */ /* Slow implementation for browsers that don't natively support .matches() */ function matchesSelector_SLOW(element, selector) { var root = element; while (root.parentNode) { root = root.parentNode; } var all = root.querySelectorAll(selector); return Array.prototype.indexOf.call(all, element) !== -1; } var CSSCore = { /** * Adds the class passed in to the element if it doesn't already have it. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ addClass: function addClass(element, className) { !!/\s/.test(className) ? "development" !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : void 0; if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasClass(element, className)) { element.className = element.className + ' ' + className; } } return element; }, /** * Removes the class passed in from the element * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @return {DOMElement} the element passed in */ removeClass: function removeClass(element, className) { !!/\s/.test(className) ? "development" !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : void 0; if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.hasClass(element, className)) { element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one .replace(/^\s*|\s*$/g, ''); // trim the ends } } return element; }, /** * Helper to add or remove a class from an element based on a condition. * * @param {DOMElement} element the element to set the class on * @param {string} className the CSS className * @param {*} bool condition to whether to add or remove the class * @return {DOMElement} the element passed in */ conditionClass: function conditionClass(element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }, /** * Tests whether the element has the class specified. * * @param {DOMNode|DOMWindow} element the element to check the class on * @param {string} className the CSS className * @return {boolean} true if the element has the class, false if not */ hasClass: function hasClass(element, className) { !!/\s/.test(className) ? "development" !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : void 0; if (element.classList) { return !!className && element.classList.contains(className); } return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1; }, /** * Tests whether the element matches the selector specified * * @param {DOMNode|DOMWindow} element the element that we are querying * @param {string} selector the CSS selector * @return {boolean} true if the element matches the selector, false if not */ matchesSelector: function matchesSelector(element, selector) { var matchesImpl = element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.msMatchesSelector || function (s) { return matchesSelector_SLOW(element, s); }; return matchesImpl.call(element, selector); } }; module.exports = CSSCore; },{"178":178}],163:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @typechecks */ var emptyFunction = _dereq_(170); /** * 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 { if ("development" !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function registerDefault() {} }; module.exports = EventListener; },{"170":170}],164:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],165:[function(_dereq_,module,exports){ "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; },{}],166:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var camelize = _dereq_(165); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; },{"165":165}],167:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var isTextNode = _dereq_(180); /*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(outerNode)) { return false; } else if (isTextNode(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; } } module.exports = containsNode; },{"180":180}],168:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var invariant = _dereq_(178); /** * 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')) ? "development" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; !(typeof length === 'number') ? "development" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; !(length === 0 || length - 1 in obj) ? "development" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; !(typeof obj.callee !== 'function') ? "development" !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; },{"178":178}],169:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = _dereq_(164); var createArrayFromMixed = _dereq_(168); var getMarkupWrap = _dereq_(174); var invariant = _dereq_(178); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = Array.from(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; },{"164":164,"168":168,"174":174,"178":178}],170:[function(_dereq_,module,exports){ "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ 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; }; module.exports = emptyFunction; },{}],171:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyObject = {}; if ("development" !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; },{}],172:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; },{}],173:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],174:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /*eslint-disable fb-www/unsafe-html */ var ExecutionEnvironment = _dereq_(164); var invariant = _dereq_(178); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? "development" !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; },{"164":164,"178":178}],175:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; },{}],176:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],177:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var hyphenate = _dereq_(176); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; },{"176":176}],178:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if ("development" !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; },{}],179:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; },{}],180:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var isNode = _dereq_(179); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; },{"179":179}],181:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only */ 'use strict'; var invariant = _dereq_(178); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function keyMirror(obj) { var ret = {}; var key; !(obj instanceof Object && !Array.isArray(obj)) ? "development" !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : void 0; for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; },{"178":178}],182:[function(_dereq_,module,exports){ "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function keyOf(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; },{}],183:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; },{}],184:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var ExecutionEnvironment = _dereq_(164); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; },{"164":164}],185:[function(_dereq_,module,exports){ 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var performance = _dereq_(184); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function performanceNow() { return performance.now(); }; } else { performanceNow = function performanceNow() { return Date.now(); }; } module.exports = performanceNow; },{"184":184}],186:[function(_dereq_,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * */ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqual; },{}],187:[function(_dereq_,module,exports){ /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyFunction = _dereq_(170); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("development" !== 'production') { (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)); } }; })(); } module.exports = warning; },{"170":170}],188:[function(_dereq_,module,exports){ 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; },{}]},{},[110])(110) });